是否可以在Angular 8中定义函数前/后处理器



使用angular 8.2.14,我有一个angular服务通过HttpClient进行一些http调用。我正在使用BehaviourSubject和相关的observable来声明http调用是否已经收到响应。这样我的html页面就可以在等待响应时显示一个mat进度微调器。

这是我的服务的一个片段

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((',并定义调用1、调用2、..、。。,callX必须由next(true(进行预处理,并由pipe finalize位进行后处理?

这只是一个因式分解的问题,因为我的代码是按原样工作的,但我在任何地方都找不到任何与这个想法相关的东西。

提前感谢

您可以尝试定义一个函数来设置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))
)
}

最新更新