【问题标题】:Angular 2 - Chaining http requestsAngular 2 - 链接 http 请求
【发布时间】:2019-12-02 21:55:43
【问题描述】:

我从 httpService 获得了一个 RxJS Observable,它是来自 Angular 的实际 http。现在,一旦我得到一个肯定的结果,我想处理我从this.retrieve() 获得的下一个 http 请求。这或多或少是连接请求。有更好的方法吗?

return this.httpService.query(data) 
        .map(data => {
            if(data.status > 1)
               this.retrieve().subscribe();
            return data;
});

【问题讨论】:

    标签: javascript http angular rxjs


    【解决方案1】:

    可以使用flatMapswitchMap 运算符来链接HTTP 请求。假设我们要发出三个请求,每个请求取决于前一个请求的结果:

    this.service.firstMethod()
        .flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult))
        .flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
        .subscribe(thirdMethodResult => {
              console.log(thirdMethodResult);
         });
    

    通过这种方式,您可以链接尽可能多的相互依赖的请求。


    更新: 从 RxJS 5.5 版开始,引入了可管道操作符,语法略有变化:

    import {switchMap, flatMap} from 'rxjs/operators';
    
    this.service
      .firstMethod()
      .pipe(
        switchMap(firstMethodResult => this.service.secondMethod(firstMethodResult)),
        switchMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
      )
      .subscribe(thirdMethodResult => {
          console.log(thirdMethodResult);
        });
    

    【讨论】:

    • 太棒了。非常感谢!
    • 另见switchMap() - switchMap - learn-rxjs
    • 如何合并所有请求的返回并返回结果?
    • 从哪里导入 flatMap?
    • 从 'rxjs/operators' 导入 {switchMap, flatMap};
    猜你喜欢
    • 2018-01-02
    • 2018-03-30
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多