angular - 在严格模式下,我应该在 angular 10 的拦截器中为 HttpRequest 提供什么类型
问题描述
我一直在使用tslint 规则附带的Angular 10上的严格模式。我已将应用程序上的几乎所有内容都修复为不包含该类型,但我不知道我可以在拦截器中为and提供哪些类型。"no-any"
any
HttpRequest
HttpEvent
我想可能有很多类型,我一直在网上寻找这样的例子,但它们大多是使用any
.
例如:我有很多post
请求,它们都将正文中的不同对象传递给服务器。我知道 中的<T>
(any)HttpRequest
代表body。我应该type variable
用所有给定的对象创建一个吗?看起来很乱。
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { catchError } from 'rxjs/operators';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = this.authService.getToken();
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
return next.handle(request).pipe(
catchError((err) => {
if (err.status !== 200) {
this.authService.logout();
}
return throwError(err);
})
);
}
}
解决方案
我通常坚持unknown
。
另一个(也许更漂亮)的解决方案可能是定义一个特殊的联合类型,或者一个通用接口。
export type ManyTypes = Type1 | Type2 | Type3;
或您可能想要使用的任何类型。
推荐阅读
- python - 仅在空白处标记 | sklearn - TfidfVectorizer | Python
- android - Android,Gradle:如何从不同的成绩文件中引用“android”块
- c - 我们首先需要传递进程和资源,而不是在结构中传递数字。例如 P1,P2,P3,R1,R2
- leaflet - Leaflet.js(或其他解决方案)缩放到放大的像素而不会模糊
- xcode - 如何修复 Xcode 11.5 编译错误。编译错误不会发生在早期版本的 Xcode 上,例如 11.3.1
- python - 为什么我的 Django/Bootstrap 项目中不断出现 multiValueDictKey 错误?
- python - 使用循环抓取网页并写入 csv
- r - 使用 purrr 从不同的数据框中选择并应用正确的模型
- android - 如何从 kotlin 的内部类调用片段方法?
- android - Android Google Fit 集成不稳定并导致需要登录错误