【问题标题】:Angular RxJS Nested Subscribe with multiple Http Requests带有多个 Http 请求的 Angular RxJS 嵌套订阅
【发布时间】:2018-12-11 11:07:50
【问题描述】:

我想知道一个接一个地发出http请求时的最佳做法是什么,特别是,我将被要求使用第一个请求的返回值。目前,我有一个嵌套订阅来解决这个问题[参见下面的代码]。

我尝试使用 RxJS 的 siwtchMap、mergeMap 和 concat,但它似乎不起作用。任何建议都会有所帮助。

onStartUp() {
    this.recordingService.getRecording(this.id)
     .subscribe(x => {
       this.recording = x;
       const params = new Chunk(this.recording, 0, 30);
       this.recordingService.getSignal(params)
        .subscribe(data => console.log(data));
     });
  }

【问题讨论】:

  • 什么不适用于switchMapmergeMap

标签: angular http rxjs rxjs6


【解决方案1】:

为什么 switchMap 在您的情况下不起作用?我认为这是最好的解决方案,switchMap 接收流的结果并返回另一个 observable 以继续流:

onStartUp() {
   this.recordingService.getRecording(this.id)
   .switchMap((x) => {
       this.recording = x;
       const params = new Chunk(this.recording, 0, 30);
       return this.recordingService.getSignal(params);  
   })
   .subscribe(data => console.log(data));
 }

如果您使用的是可管道操作符:

import { switchMap } from 'rxjs/operators';

this.recordingService.getRecording(this.id)
  .pipe(
      switchMap((x) => {
          this.recording = x;
          const params = new Chunk(this.recording, 0, 30);
          return this.recordingService.getSignal(params);  
      })
  )
  .subscribe(data => console.log(data));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-07
    • 2021-11-18
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多