是否可以在 Angular 8 中定义函数 pre/post 处理器?

Is it possible to define function pre/post processors in Angular 8?

使用 angular 8.2.14,我有一个 angular 服务通过 HttpClient 执行一些 http 调用。我正在使用 BehaviourSubject 和相关的可观察对象来说明 http 调用是否已收到响应。这样我的 html 页面就可以在等待响应时显示 mat-progress-spinner。

这是我的服务的一个片段

export class myService {

    private waitingSubject = new BehaviorSubject<boolean>(false);
    readonly waiting$ = this.waitingSubject.asObservable();

    constructor(
        private http: HttpClient
    ) { }

    public call1(): Observable<Whatever1> {
        this.waitingSubject.next(true);
        return this.http.post<Whatever1>('path/to/getWhatever1', null)
          .pipe(finalize(() => this.waitingSubject.next(false)));
    }

    public call2(): Observable<Whatever2> {
        this.waitingSubject.next(true);
        return this.http.post<Whatever2>('path/to/getWhatever2', null)
          .pipe(finalize(() => this.waitingSubject.next(false)));
    }

    public call3(): Observable<Whatever3> {
        this.waitingSubject.next(true);
        return this.http.post<Whatever3>('path/to/getWhatever3', null)
          .pipe(finalize(() => this.waitingSubject.next(false)));
    }
    ...

}

然后使用此服务的组件可以显示在 html 页中使用的微调器

<mat-progress-spinner *ngIf="myService.waiting$ | async" color="primary" mode="indeterminate"></mat-progress-spinner>

我是否有机会从我的调用函数中删除 'this.waitingSubject.next(true);' 和 '.pipe(finalize(() => this.waitingSubject.next(false)))' 并在某处定义 call1, call2, .., callX 必须由 next(true) 预处理并且 post 由管道终结位处理 ?

这只是一个分解问题,因为我的代码按原样工作,但我无法在任何地方找到与此想法相关的任何内容。

提前致谢

您可以尝试定义一个函数来设置 waitingSubject。尝试以下

export class myService {
  private waitingSubject = new BehaviorSubject<boolean>(false);
  readonly waiting$ = this.waitingSubject.asObservable();

  private waiter = (call: Observable<any>) => 
    call.pipe(
      tap(_ => this.waitingSubject.next(true)),
      finalize(() => this.waitingSubject.next(false))
    )

  constructor(private http: HttpClient) { }

  public call1(): Observable<Whatever1> {
    return this.waiter(this.http.post<Whatever1>('path/to/getWhatever1', null));
  }

  public call2(): Observable<Whatever2> {
    return this.waiter(this.http.post<Whatever2>('path/to/getWhatever2', null));
  }

  public call3(): Observable<Whatever3> {
    return this.waiter(this.http.post<Whatever3>('path/to/getWhatever3', null));
  }

  ...
}

注意:未经测试的代码,可能需要解决一些问题。

Michael D 提出的建议在稍作改动后有效:

他的建议

private waiter = (call: Observable<any>) => 
    call.pipe(
      tap(_ => this.waitingSubject.next(true)),
      finalize(() => this.waitingSubject.next(false))
    )

修改为

private waiter = (call: Observable<any>) => {
    this.waitingSubject.next(true);
    return call.pipe(
      finalize(() => this.waitingSubject.next(false))
    )
}