angular - 使用 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 调用完成之前调用,并将结果返回给调用函数。
感谢帮助!
解决方案
如果我是你,我会这样做:
// 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);
});
不需要取消订阅http
Angular 中的调用,因为它们是有限的。
现在,在您需要从中读取值的其他任何地方,您都可以与此类似地从缓存中读取它。我不喜欢这个,因为我会使用 Ngrx。继续以这种方式创建意大利面条代码。
推荐阅读
- android - 如何在我的应用程序中修复 IllegalArgumentException 改造
- python - 使用python将今天收到的电子邮件中的附件复制到文件夹
- c++ - ZMQ 上下文被终止(线程)
- python - 如何在python中动态返回当前时间
- javascript - svg url 不使用 parceljs 编译
- python - 无法更改 matplotlib 中的默认颜色图
- service - 无法在 PowerBI 服务中计划刷新
- amazon-web-services - 如何将 DynamoDB 流连接到 kinesis 流?
- javascript - 如何在数组中返回非重复值?
- angular - 将 Ionic 4 应用程序连接到同一网络上的 WebSocket