Tes*_*act 8 async-await eventemitter typescript angular
是否可以等待 Angular EventEmitter 发出,就像可以等待 ajax 调用(Angular 5 同步 HTTP 调用)一样?
我想做的是:
有一个子组件
@Component({
template: '<button (click)="emit1()">emit</button>'
})
export class ChildComponent {
@Output() dataChanged: EventEmitter<number> = new EventEmitter<number>(true); // synchronous
emit1(){
this.dataChanged.emit(1)
}
}
Run Code Online (Sandbox Code Playgroud)
以及动态创建子组件的父组件
@Component()
export class ParentComponent {
childComponentRef: ComponentRef<ChildComponent>
constructor(private resolver: ComponentFactoryResolver, private vcRef: ViewContainerRef) {}
openChild() {
const factory = this.resolver.resolveComponentFactory(ChildComponent);
this.childComponentRef = this.vcRef.createComponent(factory);
await this.childComponentRef.instance.dataChanged.toPromise()
alert('emited!')
}
}
Run Code Online (Sandbox Code Playgroud)
我想 (a) 等待,直到从子组件发出值。
AngularEventEmitter
是 RxJS 的接口扩展Subject
。它们实际上是异步的,而不是像问题中提到的同步。因此,您需要订阅它以收听发出的通知。
openChild() {
const factory = this.resolver.resolveComponentFactory(ChildComponent);
this.childComponentRef = this.vcRef.createComponent(factory);
this.childComponentRef.instance.dataChanged.subscribe(
response => { alert('emited!') }
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6262 次 |
最近记录: |