从角度4的一个组件到其他组件的数据

时间:2018-04-10 17:19:00

标签: javascript angular components

我想将数据从一个组件共享到其他组件。

我在list.component(url path:settings / list)中有一个像这样的表

enter image description here

当我点击“查看/编辑”按钮时,它会转到其他组件selected.component(url path:settings / selected),它会显示所选行的详细信息,如名称,电子邮件地址。

list.component.ts

  getAccountsList() {
    this.http.get<Company>(environment.company,
      { headers: new HttpHeaders({ 'Authorization': 'bearer localStorage.getItem("jwt_token")' }) })
      .subscribe(data => {
        this.company = data;
        console.log(data);
      });
  }

  // Memory optimization trick
  userThumb(index, company) {
    return company ? company.id : undefined;
  }

list.component.html

    <tr *ngFor="let companyData of company?.companies.data; trackBy: userThumb">
                                <td class="text-truncate">{{companyData?.name }}</td>

</tr>

1 个答案:

答案 0 :(得分:1)

对于项目列表项目选项的情况,我个人更喜欢在路径上传递所选项目的ID。 它非常简洁,在Angular文档中有很好的解释。

您需要做什么

在列表组件上: - 当您选择ViewEdit时,您将获得所选项目的ID并将其放在路径

 goToItemDetails(id) {
  this.router.navigate(['/item-details', id]);
}

详细信息组件: 当您初始化组件时,您将获得设置的ID

ngOnInit() {
   this.route.params.subscribe(params => {
       this.id = +params['id'];
       // a service that calls item by it's id from the database
    });

您可以在link

上找到更多详细信息