首页 > 解决方案 > 在严格模式下,我应该在 angular 10 的拦截器中为 HttpRequest 提供什么类型

问题描述

我一直在使用tslint 规则附带的Angular 10上的严格模式。我已将应用程序上的几乎所有内容都修复为不包含该类型,但我不知道我可以在拦截器中为and提供哪些类型。"no-any"anyHttpRequestHttpEvent

我想可能有很多类型,我一直在网上寻找这样的例子,但它们大多是使用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);
      })
    );
  }
}

标签: angularhttprequestangular-http-interceptors

解决方案


我通常坚持unknown

另一个(也许更漂亮)的解决方案可能是定义一个特殊的联合类型,或者一个通用接口。

export type ManyTypes = Type1 | Type2 | Type3;或您可能想要使用的任何类型。


推荐阅读