首页 > 解决方案 > 使用 RXJS 的 API 调用无法正常工作

问题描述

我有组件和服务。该组件正在调用正在创建 API 调用的服务函数。一旦 API 调用完成,我想调用另一个函数并传递 api 调用的结果。技术:angular、rxjs、swagger

在组件中:

of(this.customerService.getCustomerOverview(this.id)).subscribe((x)=>{
      console.log(x);
      this.getResultValues(x);
    });

在役:

getCustomerOverview(id) {
    this.localSubscriptions.push(this.apiClient.getCustomer(id, '').subscribe(result => {
      console.log(result);
      return result;
    },
      (error: any) => {

      }));
  }

错误:this.getResultValues(x); 在 API 调用完成之前调用,并将结果返回给调用函数。

感谢帮助!

标签: angularrxjs

解决方案


如果我是你,我会这样做:

// service
import { BehaviorSubject } from 'rxjs';
....
public customerCache$: BehaviorSubject<any> = new BehaviorSubject(null);
getCustomerOverview(id) {
  return this.apiClient.getCustomer(id, '');
}
.....
// component
import { of } from 'rxjs;
import { switchMap, take } from 'rxjs/operators';
.....
this.customerService.customerCache$.pipe(
  // take(1) to kill the subscription after the subscribe, I am scared of an infinite loop because of the .next in the subscribe
  take(1),
  switchMap(cache => {
     // if the cache is truthy, great, use it
     if (cache) {
       return of(cache);
     } else {
       // else make an API call
       return this.customerService.getCustomerOverview(this.id);
     }
  }),
).subscribe(x => {
  // store x as the cache
  this.customerService.customerCache$.next(x);
  // make sure this console doesn't log infinitely
  console.log(x);
  this.getResultValues(x);
});

不需要取消订阅httpAngular 中的调用,因为它们是有限的。

现在,在您需要从中读取值的其他任何地方,您都可以与此类似地从缓存中读取它。我不喜欢这个,因为我会使用 Ngrx。继续以这种方式创建意大利面条代码。


推荐阅读