首页 > 解决方案 > 如何通过以角度路由到相同的组件来传递不同的数据(对象数组)

问题描述

我的dashboard.ts. 如何将此数据传递到“ClientsListComponent”。

仪表板.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]}
      ]

客户端列表组件.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() {
  }
}

标签: angulartypescriptroutes

解决方案


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

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

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

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

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


推荐阅读