【问题标题】:Return Observable from inside nested callbacks functions从嵌套回调函数内部返回 Observable
【发布时间】:2017-09-20 15:43:47
【问题描述】:

下午好!

我目前正在使用 Angular2/4 开发一个 Web 应用程序,但我遇到了 Observables 的问题。目标是在组件内部调用一个函数,当该函数完成时,我希望执行一些代码。所以,"myComp.component.ts"文件中的代码是:

this.myService.myFunc1().subscribe(() => {
    // this code has to be executed after myFunc1() finishes.
});

问题出在 "myService.service.ts" 文件的 "myFunc1()" 函数中。该函数的结构如下:

  1. 定义函数,它返回一个Observable<Status>,其中Status对象就是{ status: 'ok' }
  2. 从另一个服务调用函数“myFunc2()”,它返回一个Observable,并做一些工作。
  3. 从另一个服务调用函数 "myFunc3()",该函数返回一个 Observable,并且必须在 "myFunc2()" 完成后执行。
  4. 从另一个服务调用函数 "myFunc4()",该函数返回一个 Observable,并且必须在 "myFunc3()" 完成后执行。
  5. { status: 'ok' } 返回到 "myComp.component.ts" 以便执行 subscribe() 中的其他代码。

所以我需要的是 (3) 一些函数的嵌套调用,每个函数都在前一个函数之后执行。最简单的方法如下:

myFunc1(): Observable<Status> {
    // some code and then call of myFunc2()
    this.myService2.myFunc2().subscribe(data => {
       // do some staff here and then call of myFunc3()
       this.myService3.myFunc3().subscribe(data2 => {
          // do some other staff and then call of myFunc4()
          this.myService4.myFunc4().subscribe(data3 => {
             // do staff and then return program flow into the Component
             return Observable.of<Status>({status: 'ok'});
          });
       });
    });
}

当然return Observable.of&lt;Status&gt;({status: 'ok'}); 不起作用。我一直在互联网和其他 Stackoverflow 问题上寻找解决方案,我发现了使用 flatMap()mergeMap()switchMap() 等。我认为这些解决方案不能在我的情况下使用,因为每个功能都必须在另一个之后执行。

我能做什么?我在这里想念什么?提前感谢您的帮助和时间!

【问题讨论】:

  • 您可以尝试使用combineLatestzip 组合多个观察者,具体取决于您的要求!
  • 首先你没有在你的函数中返回任何东西,所以它不会编译。其次,即使您在这种情况下确实返回了“订阅”,也会返回订阅而不是 Observable。使用 switchMap is 是正确的链接方式。确保在调用该方法时返回并订阅该方法。

标签: javascript angular observable


【解决方案1】:

您正在寻找的是 switchMap 或 mergeMap。 switch map 更好,如果新的出来,它会取消以前的请求。

myFunc1(): Observable<Status> {
    // some code and then call of myFunc2()
    return this.myService2.myFunc2()
      .switchMap(data => {
       // do some staff here and then call of myFunc3()
       return this.myService3.myFunc3()
      }).switchMap(data2 => {
          // do some other staff and then call of myFunc4()
          return this.myService4.myFunc4()
      }).switchMap(data3 => {
             // do staff and then return program flow into the Component
             return Observable.of<Status>({status: 'ok'});
          });
       });
    });
}

【讨论】:

  • 它有效。它还需要import 'rxjs/add/operator/switchMap';。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 2016-10-06
  • 2013-08-13
  • 1970-01-01
相关资源
最近更新 更多