【问题标题】:how to do nested http calls in Angular如何在 Angular 中进行嵌套的 http 调用
【发布时间】:2019-07-24 12:42:33
【问题描述】:

我有一个父 observable 和两个 child observable,他们从父响应中获取 trialId 并自己进行 http 调用。我尝试使用mergeMap,但它给我的错误是它不是一个函数。我怎么能这样做?

private _trialListPoll$ = timer(0, this.listRequestInterval).pipe(

    this.trialDataService.getTrailForPatient(this.patientId).mergeMap(
      (data) => {
        if (data.result.length > 0) {
          const trial = data.result[0] as TrialPhase;
          this.trialId = trial.trialId;
          this.trialStartDate = trial.startDate;
          this.trialEndDate = trial.endDate;
          this.trialData$.next(data.result[0]);
          this.loadDailyQuestionaireAnswerData(this.trialId); // child which makes http call and being subscribed somewhere
          this.loadStartEndQuestionaireData(this.trialId); // child which makes http call and being subscribed somewhere
        } else {
          this.trialStartDate = undefined;
          this.trialEndDate = undefined;
          this.trialData$.next(undefined);
        }
        this.isQuestionnaireInDateRange();
        this.isLoadingTrial$.next(false);
      }
    ),share());

【问题讨论】:

  • 你应该pipe(mergeMap))。 Observable 上只有 pipe 作为函数存在。
  • 啊好的,但现在它根本不起作用......我想我在这里遇到了类型问题
  • 对于mergeMap,你需要返回一个observable。我认为您应该将mergeMap 替换为tap,它会起作用。
  • 你能解决你的问题吗?

标签: angular rxjs observable


【解决方案1】:

一般来说,你会像这样进行嵌套调用:

  todosForUser$ = this.http.get<User>(`${this.userUrl}/${this.userName}`)
    .pipe(
      switchMap(user =>
        this.http.get<ToDo[]>(`${this.todoUrl}?userId=${user.id}`)
      )
    );

在本例中,我们通过userName获取用户,然后使用switchMap通过检索到的用户id获取相关数据。

对于多个请求,您可以这样做:

可观察

  dataForUser$ = this.http.get<User>(`${this.userUrl}/${this.userName}`)
    .pipe(
      switchMap(user =>
        combineLatest([
          of(user),
          this.http.get<ToDo[]>(`${this.todoUrl}?userId=${user.id}`),
          this.http.get<Post[]>(`${this.postUrl}?userId=${user.id}`)
        ])
      ),
      map(([user, todos, posts]) => ({
        name: user.name,
        todos: todos,
        posts: posts
      }) as UserData)
    );

数据集的接口

export interface UserData {
  name: string;
  posts: Post[];
  todos: ToDo[];
}

此代码检索第一组数据(因此我们从用户名中获得了 userId),然后使用 combineLatest 组合来自每个流的最新值。

我在这里有一个 stackblitz 示例:

https://stackblitz.com/edit/angular-todos-deborahk

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2016-08-28
    相关资源
    最近更新 更多