【问题标题】:angular2- how to communicate between two separate components?angular2-如何在两个独立的组件之间进行通信?
【发布时间】:2016-09-05 02:59:25
【问题描述】:

我正在做这个 angular2 项目。 我有 2 个组件,即WorkspacesComponent & PagesComponent

在数据库中,每个工作区包含页数。 我编写了下面的代码来填充 workspacesComponent 中的工作区列表和 PagesComponent 中的页面列表。

从数据库中获取工作空间

 this.workspaceService.getAllWorkspaces(this.baseUrl)
        .subscribe((workspaces) => {
            this.workspaces = workspaces;
            console.log(this.workspaces);
        }
        );

从数据库中获取页面

this.pagesService.getAllpages(this.baseUrl)
        .subscribe((pages) => {
            this.pages = pages;
            console.log(this.pages);
        }
        );

到目前为止,他们向我返回了正确的数据。但我想实现我将在 workspaceComponent 中选择工作区的功能,并且该工作区中的所有页面仅应在 pagesComponent 中列出。

也就是说,点击工作区时,它的索引可以传递给下面的方法。

getPagesByWorkspaceId(index:string){
    console.log(index);
}

并且此方法将相应地加载该工作区中的页面列表。 问题是我不确定如何从WorkspacesComponent 调用PagesComponent 中的方法

任何输入?

【问题讨论】:

    标签: events typescript angular eventemitter


    【解决方案1】:

    对于不处于直接父子关系的组件之间的通信,请使用共享服务来共享数据和通信。

    欲了解更多信息,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

    【讨论】:

      【解决方案2】:

      如果两个组件之间没有关系(父/子),则需要利用共享服务。

      查看这个问题了解更多详情:

      角度文档中的此链接也可以帮助您:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-08
        • 2021-01-06
        • 1970-01-01
        • 2012-07-21
        • 1970-01-01
        • 2020-01-02
        • 2014-07-14
        • 2018-03-23
        相关资源
        最近更新 更多