angular - 如何在角度服务文件中的值更改上使用异步管道触发 api 调用?
问题描述
我们有一个基于位置的应用程序。一旦用户更改位置下拉列表(在应用程序组件中),我需要调用子组件中的所有相关 API。
我怎样才能实现这个 RxJS 操作符?
我尝试了类似的方法,但无法获得预期的结果。预计使用 setLocation 函数 getOutwardReturnableData$ | 更改位置 async 在所有引用它的其他组件中被调用。
selectedLocation: string = '';
setLocation(location: string) {
this.selectedLocation = location;
}
get getOutwardReturnableData$(): Observable<IEntryOutwardReturnable> {
// console.log("DataService -> getOutwardReturnableData", this.getOutwardReturnableData$);
return this.http.post<IEntryOutwardReturnable>(
endPointData.GetOutwardReturnablMatDet,
{ LocationID: this.selectedLocation }
);
}
解决方案
尝试使用 selectedLocation 作为您的 api 调用的触发器。流(修改那个 observable)可以在构造函数中定义,也可以直接在你做声明的地方定义。
export class XYService {
private selectedLocation$ = new Subject();
outwardReturnable$: Observable<IEntryOutwardRegturnable>;
constructor() {
this.outwardReturnable$ = this.selectedLocation$.pipe(
switchMap(LocationId => this.http.post<...>(endpoint, { LocationId })
);
}
setLocation(location: string) {
this.selectedLocation$.next(location);
}
}
如果选择的位置发生变化,这里将触发一个新的 http 请求。http 请求将包含对该位置所做的最新更改的数据。switchMap
如果新位置在短时间内到达,它还会取消挂起的http 请求。
您还应该使用catchError
switchMap 中的运算符正确捕获错误。从这里您可以使用outwardReturnable$
来从流中读取数据。要在主题内设置初始值,您可以使用BehaviorSubject
.
推荐阅读
- android - 如何获得对 ActionBarDrawerToggle 的引用?
- html - 使用自动分页符打印 html 时添加页码
- swift - 有没有办法每按下一个按钮 5 次调用一个函数(Swift)?
- latex - 如何在 tikz 中定义文本内的坐标点?
- netsuite - 如何在 Netsuite 中检测父对象的确切记录类型?
- amazon-web-services - 使用 AWS Cognito 进行桌面身份验证
- django - 如何在 vuejs 发布期间设置 cookie
- python - 在二值图像上查找厚物体
- php - 使用 JWT 成功获取访问令牌后的 PARTNER_AUTHENTICATION_FAILED
- vb.net - 使用菜单条打开表单