如何使用角度4.3中的新httpClient处理未经授权的请求(状态为401或403) [英] How to handle unauthorized requests(status with 401 or 403) with new httpClient in angular 4.3

查看:129
本文介绍了如何使用角度4.3中的新httpClient处理未经授权的请求(状态为401或403)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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或无法导航到登录页面 任何帮助或建议,将不胜感激.

But I get the following error. Nothing really happens like it doesn't delete the cookie or it doesn't navigate to login page Any help or suggestions would be appreciated.

推荐答案

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

You should use your interceptor and just handle it like this:

@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服务包装器.

no need for the http service wrapper.

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

to use the router you'll need a factory provider like:

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

在提供拦截器的任何地方(可能是app.module).不要使用箭头功能.当您尝试为产品进行构建时,工厂功能不支持它们.

where ever you're providing the interceptor (probably app.module). don't use an arrow function. they aren't supported in factory functions when you try to build for prod.

工作勤奋的人: https://plnkr.co/edit/UxOEqhEHX1tCDVPDy488?p=preview

这篇关于如何使用角度4.3中的新httpClient处理未经授权的请求(状态为401或403)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆