gpt4 book ai didi

Angular 拦截器-不能将 'Observable'类型分配给 'Observable>'类型

转载 作者:行者123 更新时间:2023-12-03 15:48:57 25 4
gpt4 key购买 nike

我只是从文章中复制了此代码

import { Injectable } from "@angular/core";
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse
} from "@angular/common/http";
import { throwError, Observable, BehaviorSubject, of } from "rxjs";
import { catchError, filter, take, switchMap } from "rxjs/operators";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private AUTH_HEADER = "Authorization";
private token = "secrettoken";
private refreshTokenInProgress = false;
private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
null
);

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (!req.headers.has("Content-Type")) {
req = req.clone({
headers: req.headers.set("Content-Type", "application/json")
});
}

req = this.addAuthenticationToken(req);

return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error && error.status === 401) {
// 401 errors are most likely going to be because we have an expired token that we need to refresh.
if (this.refreshTokenInProgress) {
// If refreshTokenInProgress is true, we will wait until refreshTokenSubject has a non-null value
// which means the new token is ready and we can retry the request again
return this.refreshTokenSubject.pipe(
filter(result => result !== null),
take(1),
switchMap(() => next.handle(this.addAuthenticationToken(req)))
);
} else {
this.refreshTokenInProgress = true;

// Set the refreshTokenSubject to null so that subsequent API calls will wait until the new token has been retrieved
this.refreshTokenSubject.next(null);

return this.refreshAccessToken().pipe(
switchMap((success: boolean) => {
this.refreshTokenSubject.next(success);
return next.handle(this.addAuthenticationToken(req));
}),
// When the call to refreshToken completes we reset the refreshTokenInProgress to false
// for the next time the token needs to be refreshed
finalize(() => (this.refreshTokenInProgress = false))
);
}
} else {
return throwError(error);
}
})
);
}

private refreshAccessToken(): Observable<any> {
return of("secret token");
}

private addAuthenticationToken(request: HttpRequest<any>): HttpRequest<any> {
// If we do not have a token yet then we should not set the header.
// Here we could first retrieve the token from where we store it.
if (!this.token) {
return request;
}
// If you are calling an outside domain then do not add the token.
if (!request.url.match(/www.mydomain.com\//)) {
return request;
}
return request.clone({
headers: request.headers.set(this.AUTH_HEADER, "Bearer " + this.token)
});
}
}

我收到此错误
Type 'Observable<unknown>' is not assignable to type 'Observable<HttpEvent<any>>'.
Type 'unknown' is not assignable to type 'HttpEvent<any>'.
Property 'type' is missing in type '{}' but required in type 'HttpUserEvent<any>'.ts(2322)


如果我理解正确(至少是从尝试删除部分代码开始,则在这里引起了错误)

return this.refreshAccessToken().pipe(
switchMap((success: boolean) => {
this.refreshTokenSubject.next(success);
return next.handle(this.addAuthenticationToken(req));
}),

我应该进行哪些更改才能使其正常工作?和/或如果我只是直接使用另一个家伙示例,为什么它首先不起作用

(这是文章btw,2019年3月 https://medium.com/angular-in-depth/top-10-ways-to-use-interceptors-in-angular-db450f8a62d6,n1)

最佳答案

这里有两个问题,您需要类型转换返回到您的输出,而且finalize中缺少imports

import { Injectable } from "@angular/core";
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse
} from "@angular/common/http";
import { throwError, Observable, BehaviorSubject, of, finalize } from "rxjs";
import { catchError, filter, take, switchMap } from "rxjs/operators";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private AUTH_HEADER = "Authorization";
private token = "secrettoken";
private refreshTokenInProgress = false;
private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
null
);

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (!req.headers.has("Content-Type")) {
req = req.clone({
headers: req.headers.set("Content-Type", "application/json")
});
}

req = this.addAuthenticationToken(req);

return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error && error.status === 401) {
// 401 errors are most likely going to be because we have an expired token that we need to refresh.
if (this.refreshTokenInProgress) {
// If refreshTokenInProgress is true, we will wait until refreshTokenSubject has a non-null value
// which means the new token is ready and we can retry the request again
return this.refreshTokenSubject.pipe(
filter(result => result !== null),
take(1),
switchMap(() => next.handle(this.addAuthenticationToken(req)))
);
} else {
this.refreshTokenInProgress = true;

// Set the refreshTokenSubject to null so that subsequent API calls will wait until the new token has been retrieved
this.refreshTokenSubject.next(null);

return this.refreshAccessToken().pipe(
switchMap((success: boolean) => {
this.refreshTokenSubject.next(success);
return next.handle(this.addAuthenticationToken(req));
}),
// When the call to refreshToken completes we reset the refreshTokenInProgress to false
// for the next time the token needs to be refreshed
finalize(() => (this.refreshTokenInProgress = false))
);
}
} else {
return throwError(error);
}
})
) as Observable<HttpEvent<any>>;
}

private refreshAccessToken(): Observable<any> {
return of("secret token");
}

private addAuthenticationToken(request: HttpRequest<any>): HttpRequest<any> {
// If we do not have a token yet then we should not set the header.
// Here we could first retrieve the token from where we store it.
if (!this.token) {
return request;
}
// If you are calling an outside domain then do not add the token.
if (!request.url.match(/www.mydomain.com\//)) {
return request;
}
return request.clone({
headers: request.headers.set(this.AUTH_HEADER, "Bearer " + this.token)
});
}
}

关于 Angular 拦截器-不能将 'Observable<unknown>'类型分配给 'Observable<HttpEvent<any>>'类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59477494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com