非父子组件之间的通信

时间:2018-10-15 11:40:19

标签: angular components communication

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

1 个答案:

答案 0 :(得分: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);
    }
}
相关问题