1

我正在练习 Angular JWT 身份验证和授权。这是我的auth.interceptor.ts文件:

import { HTTP_INTERCEPTORS, HttpEvent } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpHandler, HttpRequest } from "@angular/common/http";
import { Observable } from "rxjs";

import { TokenStorageService } from "../services/token-storage.service";


const TOKEN_HEADER_KEY = "Authorization";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    
    constructor(private token:TokenStorageService) { }

    intercept(req: HttpRequest, next:HttpHandler): Observable<any> {
        let authReq = req;
        const token = this.token.getToken();
        if (token != null) {
            authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer' + token) });
        }
        return next.handle(authReq);
    }
}

export const authInterceptorproviders = [
    { provide: HTTP_INTERCEPTORS, userClass: AuthInterceptor, multi: true }
];

我从HttpRequest(第 10 行)收到此错误

Generic type 'HttpRequest<T>' requires 1 type argument(s).ts(2314)

为什么我会收到此错误?任何解决方案?

4

2 回答 2

5

'HttpRequest' 中的你应该是一个具体的复杂类型或原始类型

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      /// your code
    }
于 2021-01-05T04:56:24.883 回答
1

HttpRFesponce 是 t 的泛型类型,因为 Body:

/**
 * An outgoing HTTP request with an optional typed body.
 *
 * `HttpRequest` represents an outgoing request, including URL, method,
 * headers, body, and other request configuration options. Instances should be
 * assumed to be immutable. To modify a `HttpRequest`, the `clone`
 * method should be used.
 *
 * @publicApi
 */
export declare class HttpRequest<T> {
    readonly url: string;
    /**
     * The request body, or `null` if one isn't set.
     *
     * Bodies are not enforced to be immutable, as they can include a reference to any
     * user-defined data type. However, interceptors should take care to preserve
     * idempotence by treating them as such.
     */
    readonly body: T | null;
    
    //..
}

要修复它,您可以这样使用它:

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptor implements HttpInterceptor {
  constructor(public authService: AuthenticationService) {}

  /**
   * The Interceptors are called in the order they are defined in provider metadata.
   * @param HttpRequest request The HttpRequest is an outgoing HTTP request which is being intercepted.
   * It contains URL, method, headers, body and other request configuration.
   * @param HttpHandler next The HttpHandler dispatches the HttpRequest to the next Handler using the method HttpHandler.handle.
   * The next handler could be another Interceptor in the chain or the Http Backend.
   */
  intercept(request: HttpRequest<any> /* <any> added here */, next: HttpHandler): Observable<HttpEvent<any>> {

    // this.is a sample
    request = request.clone({
      setHeaders: {
        Authorization: 'Bearer ' + JSON.parse(this.authService.getToken())
      }
    });
    return next.handle(request);
  }
}
于 2021-01-05T05:01:35.593 回答