简体   繁体   English

如何在 angular 中使用 observable 进行一致的 http 调用?

[英]How to make consistent http calls with observable in angular?

I need to make chained http calls to api.我需要对 api 进行链式 http 调用。 In first response I get observable, then I use map operator and return this result:在第一个响应中,我得到 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']
          };
       })
     );
  }

Then I need to make another http call with parameter result['Experts'] , which is array with ID's.然后我需要使用参数result['Experts']进行另一个 http 调用,它是带有 ID 的数组。 How can I pass that parameter to next call?如何将该参数传递给下一次调用? I've tried to use SwitchMap, but there is no result.我尝试使用 SwitchMap,但没有结果。 And how to save response data from this calls?以及如何保存此调用的响应数据? because I need to use both in my template.因为我需要在我的模板中同时使用两者。

switchMap is the right operator to use to chain http calls. switchMap是用于链接 http 调用的正确运算符。 Whenever the first observable emits, you can create a second observable using the value emitted.每当第一个 observable 发出时,您就可以使用发出的值创建第二个 observable。

In your example:在你的例子中:

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)
   );
}

As for saving the data, you can either do this in a tap after each observable as above, or you can use async | pipe至于保存数据,您可以在每个 observable 之后点击执行此操作,或者您可以使用async | pipe async | pipe in the template.模板中的async | pipe

If there is no result, it might be that you are not subscribing to the observable:如果没有结果,则可能是您没有订阅 observable:

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

Again, you can do this manually as above or use async | pipe同样,您可以像上面那样手动执行此操作或使用async | pipe async | pipe in the template.模板中的async | pipe

Check out https://angular.io/guide/observables查看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')
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM