【问题标题】:Invoke a function in a sibling component when an event happens in current component当前组件中发生事件时调用同级组件中的函数
【发布时间】:2018-08-07 02:44:24
【问题描述】:

我的应用程序有一个父组件和两个兄弟组件。

<feed>
 <status></status>
 <post></post>
</feed>

我想要实现的是,当我在状态组件(基本上是一个文本字段)中编写内容并提交时,我应该将该数据传递到 post 组件并调用 post 组件中的另一个函数来更新其视图。但我不知道如何做到这一点。任何帮助将不胜感激。

【问题讨论】:

    标签: angular angular-components


    【解决方案1】:

    您需要实现一个服务并拥有一个事件发射器,然后您可以将该服务注入两个组件并从status 组件发出并在post 组件中监听它

    common.service.ts:

    @Output() public somethingChanged: EventEmitter<any> = new EventEmitter();
    

    status.component.ts:

    someFunc() {
        this.commonService.somethingChanged.emit({
            data: "Dummy Data For Post Component"
        })
    }
    

    post.component.ts:

    constructor(
        public commonService: CommonService
    ) {
        this.commonService.somethingChanged.subscribe((data: any) => {
            console.log("Data from status component", data);
        })
    }
    

    现在,每当调用 status 组件中的 someFunc 时,都会执行 post 组件中的侦听器。您需要确保两个组件共享相同的CommonService 实例,即statuspost 组件都是相同NgModule 的一部分,如果它们不是您将需要创建CommonService 的单例使用 forRoot 的共享模块。

    【讨论】:

    • 这对我也有帮助,我不知道服务可以有 @Output 。
    猜你喜欢
    • 2019-12-11
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2019-07-18
    相关资源
    最近更新 更多