【问题标题】:How to make consistent http calls with observable in angular?如何使用可观察的角度进行一致的http调用?
【发布时间】:2020-05-11 04:59:31
【问题描述】:

我需要对 api 进行链式 http 调用。在第一个响应中,我得到了 observable,然后我使用 map 运算符并返回这个结果:

     getAreaByKey(key: string): Observable<Area> {
       return this.http.get<any[]>(`${this.api}/areas/${key}`).pipe(
        map(result => {
          return {
             'key': result['Key'],
             'name': result['Description'],
             'experts': result['Experts']
          };
       })
     );
  }

然后我需要使用参数result['Experts'] 进行另一个http 调用,该参数是带有ID 的数组。如何将该参数传递给下一次调用?我尝试使用 SwitchMap,但没有结果。以及如何保存此调用的响应数据?因为我需要在我的模板中同时使用这两者。

【问题讨论】:

标签: angular rxjs


【解决方案1】:

switchMap 是用于链接 http 调用的正确运算符。每当第一个 observable 发出时,您都可以使用发出的值创建第二个 observable。

在你的例子中:

getAreaByKey(key: string): Observable<Area> {
   return this.http.get<any[]>(`${this.api}/areas/${key}`).pipe(
      map(result => {
         return {
            'key': result['Key'],
            'name': result['Description'],
            'experts': result['Experts']
         };
      }),
      tap(res1 => // save the first response here),
      switchMap(res1 => this.anotherHttpCall(res.experts)),
      tap(res2 => // save the second response here)
   );
}

至于保存数据,您可以在上述每个 observable 之后点击执行此操作,也可以在模板中使用 async | pipe

如果没有结果,可能是你没有订阅 observable:

const obs$ = this.getAreaByKey();  // the observable is defined but the http call has not been made
obs$.subscribe();  // http call is triggered

同样,您可以像上面一样手动执行此操作,也可以在模板中使用async | pipe

【讨论】:

  • 如果你想从两个 http 调用中发出结果,你可以这样做 switchMap(res1 =&gt; this.anotherHttpCall(res1.experts).pipe(map(res2 =&gt; [res1, res2])))
【解决方案2】:

查看https://angular.io/guide/observables

myObservable.subscribe(
   x => console.log('Observer got a next value: ' + x),
   err => console.error('Observer got an error: ' + err),
  () => console.log('Observer got a complete notification')
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多