gpt4 book ai didi

angular - 如何使用 Angular 4.3 中的新 httpClient 处理未经授权的请求(状态为 401 或 403)

转载 作者:太空狗 更新时间:2023-10-29 17:04:07 27 4
gpt4 key购买 nike

我有一个 auth-interceptor.service.ts 来处理请求

import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Cookie} from './cookie.service';
import {Router} from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set(Cookie.tokenKey, Cookie.getToken())});
// Pass on the cloned request instead of the original request.
return next.handle(authReq).catch(this.handleError);
}

private handleError(err: HttpErrorResponse): Observable<any> {
console.log(err);
if (err.status === 401 || err.status === 403) {
Cookie.deleteUser();
this.router.navigateByUrl(`/login`);
return Observable.of(err.message);
}
// handle your auth error or rethrow
return Observable.throw(err);
}
}

但是我收到以下错误。没有真正发生,就像它没有删除 cookie 或没有导航到登录页面如有任何帮助或建议,我们将不胜感激。

enter image description here

最佳答案

你应该使用你的拦截器并像这样处理它:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router) { }

private handleAuthError(err: HttpErrorResponse): Observable<any> {
//handle your auth error or rethrow
if (err.status === 401 || err.status === 403) {
//navigate /delete cookies or whatever
this.router.navigateByUrl(`/login`);
// if you've caught / handled the error, you don't want to rethrow it unless you also want downstream consumers to have to handle it as well.
return of(err.message); // or EMPTY may be appropriate here
}
return throwError(err);
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set(Cookie.tokenKey, Cookie.getToken())});
// catch the error, make specific functions for catching specific errors and you can chain through them with more catch operators
return next.handle(authReq).pipe(catchError(x=> this.handleAuthError(x))); //here use an arrow function, otherwise you may get "Cannot read property 'navigate' of undefined" on angular 4.4.2/net core 2/webpack 2.70
}
}

不需要 http 服务包装器。

要使用路由器,您需要工厂供应商,例如:

 providers: [
{
provide: HTTP_INTERCEPTORS,
useFactory: function(router: Router) {
return new AuthInterceptor(router);
},
multi: true,
deps: [Router]
},
.... other providers ...
]

您在哪里提供拦截器(可能是 app.module)。不要使用箭头功能。当您尝试为产品构建时,它们在工厂功能中不受支持。

工作代码:https://plnkr.co/edit/UxOEqhEHX1tCDVPDy488?p=preview

关于angular - 如何使用 Angular 4.3 中的新 httpClient 处理未经授权的请求(状态为 401 或 403),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46017245/

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