[英]Communication between non-parent-child components
I just want to do some experiment. 我只想做一些实验。 So when I click a button of a A component, some function of a B component should invoke. 因此,当我单击A组件的按钮时,应调用B组件的某些功能。 But I don't know how to do that if these components are not parent child to each other. 但是,如果这些组件不是彼此的父子组件,我不知道该怎么做。 Can you please help me 你能帮我么
When there is no child-parent relationship between components 组件之间没有子代关系时
You should create a service having a Subject
and inject this service in both of these components. 您应该创建一个具有Subject
的服务,并将该服务注入这两个组件中。
some.service.ts some.service.ts
@Injectable()
export class SomeService {
public testSubject = new Subject<string>();
}
comp-a.component.ts COMP-a.component.ts
export class CompAComponent {
constructor(private someService: SomeService) {
}
btnClickHandler() {
this.someService.testSubject.next('clicked');
}
}
comp-b.component.ts COMP-b.component.ts
export class CompBComponent {
constructor(private someService: SomeService) {
this.someService.testSubject.subscribe(next => { this.someFunction(data);});
}
someFunction(msg) {
console.log(msg);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.