如何解决Angular 11 通用类型“HttpRequest<T>”需要 1 个类型参数ts(2314)
我正在练习 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)
为什么我会收到这个错误?任何解决方案?
解决方法
'HttpRequest' 中的你应该是一个具体的复杂或原始类型
intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
/// your code
}
,
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,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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。