非父子组件之间的通信



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

当组件之间没有子父关系时

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

一些.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);
}
}

最新更新