@jornare 在他的解决方案中有一个好主意。他正在处理多个请求的案件。然而,代码可以写得更简单,无需创建新的可观察对象并将请求存储在内存中。下面的代码还使用 RxJS 6 和可管道运算符:
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpInterceptor,
HttpResponse
} from '@angular/common/http';
import { finalize } from 'rxjs/operators';
import { LoadingService } from '@app/services/loading.service';
import { of } from 'rxjs';
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
private totalRequests = 0;
constructor(private loadingService: LoadingService) { }
intercept(request: HttpRequest<any>, next: HttpHandler) {
this.totalRequests++;
this.loadingService.setLoading(true);
return next.handle(request).pipe(
finalize(() => {
this.totalRequests--;
if (this.totalRequests === 0) {
this.loadingService.setLoading(false);
}
})
);
}
}
将此拦截器服务添加到您的模块提供程序中:
@NgModule({
// ...
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true }
]
})
export class AppModule { }
这是一个例子LoadingService
执行:
@Injectable()
export class LoadingService {
private isLoading$$ = new BehaviorSubject<boolean>(false);
isLoading$ = this.isLoading$$.asObservable();
setLoading(isLoading: boolean) {
this.isLoading$$.next(isLoading);
}
}
以下是您如何使用LoadingService
在组件中:
@Component({
selector: 'app-root',
template: `
<ng-container *ngIf="loadingService.isLoading$ | async">
<i class="loading"></i>
</ng-container>
<router-outlet></router-outlet>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
constructor(public loadingService: LoadingService) {}
}