gpt4 book ai didi

angular - 如何使用 Observable 调用等待事件订阅者完成

转载 作者:太空狗 更新时间:2023-10-29 18:24:45 25 4
gpt4 key购买 nike

我有两个组件。子组件有一个事件(EventEmitter)。父组件具有长时间方法的处理程序。

我需要等待完成我的方法 (longTimeMethod) 的执行,然后再执行进一步的操作。方法继续将近 5 秒。

我想一致地执行所有步骤(1 -> 2 -> 3 -> 4 -> 5)。

但现在序列是 1 -> 2 -> 4 -> 5 -> 3

@Component({
selector: 'child-selector',
template: '<>********</>'
})
export class ChildComponent{
@Output() childEvent = new EventEmitter();

someFunction() {
// Step 1: event emit

this.childEvent.emit();
// Step 5: Subscribers execution finished
// Some code which should to reached after all event subscribers
}
}

@Component({
selector: 'parent-selector',
template: '<child-selector (childEvent)="handleChildEvent()"></child-selector>'
})

export class ParentComponent{
// Step 2: handler start
handleChildEvent() {
// this.longTimeMethod return Observable<void>
this.myService.longTimeMethod()
.subscribe(() => {
// Step 3: Method executing finished
});
// Step 4: Another code
}
}

我尝试使用异步等待方法:

async handleChildEvent() {
// this.longTimeMethod return Observable<void>
await this.myService.longTimeMethod().toPromise()
.then(() => {
// Step 3: Method executing finished
});
// Step 4: Another code
}

序列已更改,但仍然不正确:1 -> 2 -> 5 -> 3 -> 4。如何实现正确的行为?

最佳答案

为了延迟第 5 步,从 child 发出回调。

export class ChildComponent{
@Output() childEvent = new EventEmitter();

someFunction() {
// Step 1: event emit
this.childEvent.emit(execStep5);
}

execStep5() {
// Step 5: Subscribers execution finished
// Some code which should to reached after all event subscribers
}
}

准备好后在父级执行execStep5

handleChildEvent(execStep5) {
...
// Step 4: Another code
execStep5();

对于step3 & step4,将subscribe改为mapthen订阅并执行step4和回调。
不要使用 await/async,因为 rxjs 已经有了这些工具——不要混合使用这两种方法。

export class ParentComponent{
// Step 2: handler start
handleChildEvent(execStep5) {
// this.longTimeMethod return Observable<void>
this.myService.longTimeMethod()
.map(() => {
// Step 3: Method executing finished
return Observable.of('done');
})
.subscribe(() => {
// Step 4: Another code
execStep5();
});
}
}

可能有更短的代码来执行此操作,但这应该可行。

关于angular - 如何使用 Observable 调用等待事件订阅者完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47173454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com