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

标签 angular typescript rxjs observable

我有两个组件。子组件有一个事件(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/

相关文章:

javascript - Typescript 函数类型推断

Angular 6 : Property 'catch' does not exist on type 'Observable<Response>' ?

html - 根据 Angular 4 中的屏幕大小更改内容的显示方式

Angular 2排序和过滤

javascript - 在 Typescript/Javascript 中导出带有别名的元素

angular - 订阅在服务中意外取消(来自扩展路由组件)

angular - 如何用switchMap取消http请求?

angular - 行为主体初始值是否为空?

javascript - 更新搜索结果的计数并根据用户在对象数组中搜索的次数更改选择

angular 2 material matTooltip 多行