首页 > 解决方案 > 如何在角度服务文件中的值更改上使用异步管道触发 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 }
    );
}

标签: angulartypescriptrxjsrxjs-pipeable-operators

解决方案


尝试使用 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 请求。

您还应该使用catchErrorswitchMap 中的运算符正确捕获错误。从这里您可以使用outwardReturnable$来从流中读取数据。要在主题内设置初始值,您可以使用BehaviorSubject.


推荐阅读