当我从 ws 获取事件时,我想使用事件发射器:
我有这个函数可以获取事件,当我有事件时我想调用其他组件中的函数。
组件 A, typescript 代码:
@Output() notify: EventEmitter<any> = new EventEmitter();
getSocketevent() {
this.socket.on('data', (data) => {
this.notify.emit(data)
});
}
组件A,html代码:
<app-component-B (click)='getSocketevent()'></app-component-B>
在组件B中我想调用这个函数:
getprod() {
this.ws.getallprod().subscribe(res => {
this.dataSource = new MatTableDataSource(res);
this.dataSource.paginator = this.paginator
})
}
当我在组件 A 中收到此函数的事件时,如何调用组件 B 中的函数?
最佳答案
来自Component Interaction > Parent calls an @ViewChild()
When the parent component class requires that kind of access, inject the child component into the parent as a
ViewChild
.
在你的情况下,它是:
// A component.ts
....
@ViewChild(BComponent, {static: false})
private bComponent: BComponent;
getSocketevent() {
this.socket.on('data', (data) => {
// this.notify.emit(data)
this.bComponent.getprod();
});
}
在这种情况下,您可以看到您实际上并不需要使用 EventEmitter
。
关于angular - 当我在组件 A 中收到此函数的事件时,如何调用组件 B 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57337170/