我创建了一个ComponentMessengerService
,它使用事件发射器来允许两个子组件之间的通信。input
组件应该通过在其构造函数中使用注入的服务来向output
组件发送信息。
Epic
只是我制作的一个自定义模型。
组件信使服务源代码:
@Injectable({
providedIn: 'root'
})
export class ComponentMessengerService {
epicNumberUpdated = new EventEmitter<string>();
epicTitleUpdated = new EventEmitter<string>();
epicListUpdated = new EventEmitter<Epic[]>();
sendEpicNumber(epicNumber: string){
this.epicNumberUpdated.emit(epicNumber);
}
sendEpicTitle(epicTitle: string){
this.epicTitleUpdated.emit(epicTitle)
}
sendEpicList(epicList: Epic[]){
this.epicListUpdated.emit(epicList)
}
}
输出组件源代码:
export class OutputComponent implements OnInit {
public epicTitle: string;
public epicNumber: string;
public epicList: Epic[] = [];
constructor(private componentMessenger: ComponentMessengerService) {
this.subscribeAll();
}
subscribeAll(){
this.componentMessenger.epicListUpdated.subscribe(
(epicList: Epic[]) => {
this.epicList = epicList; })
this.componentMessenger.epicTitleUpdated.subscribe(
(epicTitle: string) => { this.epicTitle = epicTitle })
this.componentMessenger.epicNumberUpdated.subscribe(
(epicNumber: string) => {
this.epicNumber = epicNumber; })
}
}
输出的属性是绑定到html元素的数据,并且应该在组件的属性接收到可观测性之后显示。我已经调试了我的应用程序,可以确认input
组件确实在发送可观测值。不幸的是,当我尝试在subscribeAll()
中添加console.log((语句来验证事件发射器是否接收到任何数据时,这行代码从未执行过。
您是否尝试在ngOnInit中调用subscribeAll((方法?
Constructor和ngOnInit 之间的区别
更新
我会用";主题";我认为EventEmitter需要使用@Output((,而不是EventEmitter。
我们有Subject
和BehaviorSubject
。
@Injectable({
providedIn: 'root'
})
export class ComponentMessengerService {
epicNumberUpdated$ = new Subject<string>();
epicTitleUpdated$ = new Subject<string>();
epicListUpdated$ = new Subject<Epic[]>();
sendEpicNumber(epicNumber: string): void {
this.epicNumberUpdated$.next(epicNumber);
}
sendEpicTitle(epicTitle: string): void {
this.epicTitleUpdated$.next(epicTitle)
}
sendEpicList(epicList: Epic[]): void {
this.epicListUpdated$.next(epicList)
}
}
不要忘记Observables的退订,因为你可能会有内存泄漏。
export class OutputComponent implements OnInit, OnDestroy {
epicTitle: string;
epicNumber: string;
epicList: Epic[] = [];
private unsubscribe$ = new Subject<void>();
constructor(private componentMessenger: ComponentMessengerService) {}
ngOnInit(): void {
initializeListeners();
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
private initializeListeners(): void {
this.componentMessenger.epicListUpdated$
.pipe(takeUntil(this.unsubscribe$))
.subscribe((epicList: Epic[]) => {
this.epicList = epicList;
});
this.componentMessenger.epicTitleUpdated$
.pipe(takeUntil(this.unsubscribe$))
.subscribe((epicTitle: string) => {
this.epicTitle = epicTitle;
});
this.componentMessenger.epicNumberUpdated$
.pipe(takeUntil(this.unsubscribe$))
.subscribe((epicNumber: string) => {
this.epicNumber = epicNumber;
});
}
}