【问题标题】:How can I pass different data(object array) by routing to same components in angular如何通过以角度路由到相同的组件来传递不同的数据(对象数组)
【发布时间】:2019-09-22 13:51:28
【问题描述】:

我的dashboard.ts 中有两个不同的“Clients[]”数组。 如何将此数据传递到“ClientsListComponent”。

dashboard.html

<a routerLink="dashboard/my-clients" >My Clients</a>
<a routerLink="dashboard/all-clients">All Clients</a>

app.module.ts

RouterModule.forRoot(
      [ { path: '', component: LoginComponent},
        { path: 'dashboard', canActivate: [AuthguardGuard], component: DashboardComponent},
        { path: 'dashboard/add-new-client', component: ClientFormComponent, canActivate: [AuthguardGuard]},
        { path: 'dashboard/all-clients', component: ClientsListComponent, canActivate: [AuthguardGuard]},
        { path: 'dashboard/my-clients', component: ClientsListComponent, canActivate: [AuthguardGuard]}
      ]

ClientsListComponent.ts

@Component({
  selector: 'clients-list',
  templateUrl: './clients-list.component.html',
  styleUrls: ['./clients-list.component.css']
})
export class ClientsListComponent implements OnInit {

  @Input() clients: Client[] = []; // I print this data on screen.
  @Input() title: '';
  constructor() { }

  ngOnInit() {
  }
}

【问题讨论】:

    标签: angular typescript routes


    【解决方案1】:

    使用 queryParams 可以传递数据

    发送中

    import { Router } from '@angular/router';
    this.router.navigate([ '/your-route' ], { queryParams: { key: va1, keyN: valN } });
    

    接收

    import { ActivatedRoute } from '@angular/router';
    this.activatedRoute.queryParams.subscribe(params => {
      let value_1 = params['key'];
      let value_N = params['keyN'];
    

    });

    【讨论】:

      【解决方案2】:

      有几种方法可以做到这一点。可以使用 export 关键字导出 dashboard.ts 中保存数组的变量。然后另一个组件可以使用import 语句访问该数组。

      另一种方法是使用在创建组件时传递的构造函数参数,在组件定义中使用 @Input() 装饰器,就像您当前拥有的一样。

      在父组件的模板中,可以使用以下语法传递构造函数参数:

      <myapp-clientslist 
          [arg1]="arg1" [arg2]="arg2">
      </myapp-clientslist>
      

      双引号中的字符串被评估为 JavaScript。当然,这要求父组件可以使用这些变量,或者通过 URL 参数、导入语句等以相同的方式被另一个父组件接收。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-10
        • 2018-09-19
        • 1970-01-01
        • 2019-07-04
        • 1970-01-01
        • 2020-03-04
        • 2020-07-06
        • 2018-07-11
        相关资源
        最近更新 更多