如何以角度对服务文件中的值更改使用异步管道触发api调用?

时间:2020-06-22 09:56:19

标签: angular typescript rxjs rxjs-pipeable-operators

我们有一个基于位置的应用程序。一旦用户更改了位置下拉列表(在应用程序组件中),我需要在子组件中调用所有相关的API。

如何实现RxJS运算符?

我尝试过类似的操作,但无法获得预期的结果。 使用setLocation函数getOutwardReturnableData $期望更改位置。在所有引用了它的其他组件中调用了异步。

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

1 个答案:

答案 0 :(得分:1)

尝试将selectedLocation用作api调用的触发器。可以在构造函数内部或直接在声明的位置定义流(对可观察对象的修改)。

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请求。

您还应该使用switchMap中的catchError运算符正确地捕获错误。在这里,您可以使用outwardReturnable$从流中读取数据。要使主题具有初始值,可以使用BehaviorSubject