代码之家  ›  专栏  ›  技术社区  ›  yer

角度4中从一个组件到另一个组件的数据

  •  0
  • yer  · 技术社区  · 7 年前

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

    我在名单上有一张桌子。组件(url路径:设置/列表)如下

    enter image description here

    当我单击“查看/编辑”按钮时,它会转到其他选定的组件。组件(url路径:设置/选定),显示选定行的详细信息,如名称、电子邮件地址。

    列表组成部分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;
      }
    

    列表组成部分html

        <tr *ngFor="let companyData of company?.companies.data; trackBy: userThumb">
                                    <td class="text-truncate">{{companyData?.name }}</td>
    
    </tr>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   BELLIL    7 年前

    对于以下情况 项目列表 项目 选择,我个人更喜欢在路径上传递所选项目的id。 它简单明了,在角度文档中有很好的解释。

    你需要做什么

    在列表组件上 : -选择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