我正在 Angular 16 中的
HttpInterceptor
的帮助下制作应用程序级“加载旋转器”。
在
app\services\interceptor.service.ts
我有:
import { Injectable } from '@angular/core';
import { HttpInterceptor,HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { SpinnerService } from './spinner.service';
@Injectable({
providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {
constructor(private spinnerService: SpinnerService) { }
public intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
this.spinnerService.show();
return next.handle(req).pipe(
finalize(() => {
this.spinnerService.hide();
})
);
}
}
在
app\services\spinner.service.ts
:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SpinnerService {
private spinnerCounter = new BehaviorSubject<number>(0);
spinnerCounter$ = this.spinnerCounter.asObservable();
public show() {
this.spinnerCounter.next(this.spinnerCounter.value + 1);
}
public hide() {
this.spinnerCounter.next(this.spinnerCounter.value - 1);
}
}
我已将
spinnerService
导入到 app\app.component.ts
中,并将微调器添加到 app\app.component.html
。
<app-loading-spinner *ngIf="spinnerService.spinnerCounter$ | async"></app-loading-spinner>
HTTP 请求之间永远不会显示
app-loading-spinner
组件。我做错了什么以及如何解决这个问题?
您必须指定您在
HttpInterceptor
提供商中提供 AppModule
,否则它不会自行执行任何操作 :
@NgModule({
providers: [
BypassSanitizePipe,
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true,
},
],
bootstrap: [AppComponent],
})
export class AppModule {}
这是更新后的 StackBlitz :
https://stackblitz.com/edit/stackblitz-starters-lhqg8v?file=src%2Fapp%2Fapp.module.ts