我正在实现一个加载微调器,它通过 HttpInterceptorFn 使用此博客文章作为指导运行我的所有 http 请求:https://blog.angular-university.io/angular-loading-indicator/
正在加载.interceptor.ts
export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
const loadingSpinnerService = inject(LoadingSpinnerService);
console.log('SkipLoading: ', req.context.get(SkipLoading));
if (req.context.get(SkipLoading)) {
return next(req);
}
loadingSpinnerService.setIsLoading(true);
return next(req).pipe(
finalize(() => {
loadingSpinnerService.setIsLoading(false);
}),
);
};
从loading-spinner.service.ts导出的HttpContextToken
export const SkipLoading = new HttpContextToken<boolean>(() => false);
refreshToken API 调用,我希望跳过微调器
refreshToken() {
return this.http.post<TokenResponse>(
this.apiUrl + '/Token/refresh/' + this.siteUserId$.value?.toString(),
{ context: new HttpContext().set(SkipLoading, true) },
);
}
使用 console.log() 我注意到我的 SkipLoading 令牌始终为 false。使用 HttpInterceptorFn 而不是 HttpInterceptor 类时,在实现上有什么不同吗?
编辑:将 API 类型更改为 GET 后,上下文令牌按预期计算为 true。但我一定还是做错了什么,因为我也需要这个功能来处理 POST 请求。
对于
post
,文档中给出的语法如下:
post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; context?: HttpContext | undefined; observe?: "body" | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType: "arraybuffer"; withCredentials?: boolean | undefined; transferCache?: boolea...): Observable<ArrayBuffer>;
请注意,第二个参数是 post 请求的正文,因此
context
应作为第三个参数传入一个对象。
refreshToken() {
return this.http.post<TokenResponse>(
this.apiUrl + '/Token/refresh/' + this.siteUserId$.value?.toString(),
null, { context: new HttpContext().set(SkipLoading, true) },
);
}