【问题标题】:Communication between non-parent-child components非父子组件之间的通信
【发布时间】:2019-03-19 20:04:51
【问题描述】:

我只是想做一些实验。因此,当我单击 A 组件的按钮时,应调用 B 组件的某些功能。但是如果这些组件不是彼此的父子,我不知道该怎么做。你能帮帮我吗

【问题讨论】:

标签: angular components communication


【解决方案1】:

当组件之间没有父子关系

您应该创建一个具有Subject 的服务并将该服务注入这两个组件中。

some.service.ts

@Injectable()
export class SomeService {
   public testSubject = new Subject<string>();
}

comp-a.component.ts

export class CompAComponent {
    constructor(private someService: SomeService) {
    }

    btnClickHandler() {
       this.someService.testSubject.next('clicked');
    }
}

comp-b.component.ts

export class CompBComponent {

    constructor(private someService: SomeService) {
       this.someService.testSubject.subscribe(next => { this.someFunction(data);});
    }

    someFunction(msg) {
       console.log(msg);
    }
}

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 2021-03-11
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多