【问题标题】:The API call with RXJS is not working properly使用 RXJS 的 API 调用无法正常工作
【发布时间】:2020-03-06 10:16:42
【问题描述】:

我有组件和服务。该组件正在调用正在创建 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 调用完成之前调用,并将结果返回给调用函数。

感谢您的帮助!

【问题讨论】:

  • Angular 有一个内置的 http 客户端,它返回一个 observable。我建议看一下他们的示例,因为您执行此操作的方式比应有的复杂得多。 angular.io/guide/http
  • 真的,这只是你不能从订阅内部返回的问题。移除 subscribe 并返回一个 observable。然后你也可以删除of()。请记住,您不能从订阅中返回,只是您可以真正从节点经典回调中返回。

标签: angular rxjs


【解决方案1】:

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

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

在 Angular 中没有必要取消订阅 http 调用,因为它们是有限的。

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

【讨论】:

  • 感谢 AliF50。这是我以前使用过的一个场景。这种情况的一个问题是,如果我想第二次调用该 API 的结果。假设我第一次调用 API 并将数据分配给变量 getCustomerOverview(id) { if(!this.customerOverview){ this.customerOverview=this.apiClient.getCustomer(id, ''); } 返回 this.customerOverview;我的变量是一个可观察的,无论如何它都会创建一个 API 调用。你会如何解决这个问题?
  • 如果您已经调用了该服务,您不想调用它吗?
  • 我想调用服务,但如果数据存在,不要第二次调用 API。但是,我的变量是可观察的,并且无论如何都会调用 API。我在网络中看到它
  • 你不能用if 声明来做吗?查看我的编辑。
  • 它正在工作。很好的解决方案!谢谢。如果有针对该问题的 Rxjs 解决方案,即调用服务并返回 observable 而不调用 API,那么这将是多么有趣。但是,您的解决方案是很好的工作版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多