【问题标题】:rxjs - Angular: How to wait for an Observable function, to call another function that returns an Observable?rxjs - Angular:如何等待 Observable 函数,调用另一个返回 Observable 的函数?
【发布时间】:2021-07-26 19:48:22
【问题描述】:

我在一个服务中有 2 个 API 调用,每个都返回一个 Observable,在我的组件中我有一些条件,如果为真,我必须调用这两个函数,但我需要等待 get() 调用,所以我可以使用 get 调用返回的参数执行 post 函数。如果为 false,我只想使用已定义的参数调用 post 函数。

服务:

  get(id: string) {
    return this.http.get<any>('get path');
  }

  post(data: data) {
    return this.http.post<any>('post path', {data: data});
  }

组件:

  execute() {
    if (condition) {
      this.service.get(id).subscribe( (res) =>
        // ...
        this.data = res.data;
        post(data).subscribe(() => // do stuff...);
      );
    } else { post(data).subscribe(() => // do stuff...); }
   }

我不想为 post 调用重复代码,或者如果根本不可能,就不要在另一个 subscribe() 中使用 subscribe()。我怎样才能做到这一点?没有异步等待。

提前致谢

【问题讨论】:

标签: angular rxjs rxjs-observables rxjs-pipeable-operators


【解决方案1】:

您可以使用 RxJS switchMap 运算符从一个可观察对象映射到另一个(在您的情况下是 GET 到 POST),并使用 RxJS iif 函数有条件地返回一个可观察对象。

试试下面的

execute() {
  const getPost$ = this.service.get(id).pipe(
    switchMap((res: any) => {
      this.data = res.data;
      return this.service.post(data);
    })
  );


  iif(
    () => condition,
    getPost$,
    this.service.post(data)
  ).subscribe(
    (res: any) => { 
      // handle response
    },
    (error: any) => {
      // handle error
    }
  );
}

【讨论】:

    【解决方案2】:

    另一种解决方案可能如下所示:

    const source$ = condition
      ? this.service.get(id) // Get new data
      : of(this.data); // Use already defined data
    
    source$.pipe(
      concatMap(data => this.service.post(data)), 
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 2021-08-28
      相关资源
      最近更新 更多