How to handle unauthorized requests(status with 401 or 403) with new httpClient in angular 4.3

前端 未结 3 890
长发绾君心
长发绾君心 2020-12-25 14:18

I have an auth-interceptor.service.ts to handle the requests

import {Injectable} from \'@angular/core\';
import {HttpErrorResponse, HttpEvent, Ht         


        
3条回答
  •  猫巷女王i
    2020-12-25 15:02

    From the @bryan60 suggestion I made few changes to his solution

    In app.module.ts:

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

    and in auth-interceptor.service.ts:

    import {Injectable, Injector} 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';
    import {UserService} from './user.service';
    import {ToasterService} from '../toaster/toaster.service';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';
    
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
        constructor(private injector: Injector) {}
    
        private handleError(err: HttpErrorResponse): Observable {
            let errorMsg;
            if (err.error instanceof Error) {
                // A client-side or network error occurred. Handle it accordingly.
                errorMsg = `An error occurred: ${err.error.message}`;
            } else {
                // The backend returned an unsuccessful response code.
                // The response body may contain clues as to what went wrong,
                errorMsg = `Backend returned code ${err.status}, body was: ${err.error}`;
            }
            if (err.status === 404 || err.status === 403) {
                this.injector.get(UserService).purgeAuth();
                this.injector.get(ToasterService).showError(`Unauthorized`, errorMsg);
                this.injector.get(Router).navigateByUrl(`/login`);
            }
            console.error(errorMsg);
            return Observable.throw(errorMsg);
        }
    
        intercept(req: HttpRequest, next: HttpHandler): Observable> {
            // 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(err => this.handleError(err));
        }
    }
    

    If you are using AOT in building try:

    export function authInterceptorFactory(injector: Injector) {
        return new AuthInterceptor(injector);
    }
    
    providers: [
             {
                provide: HTTP_INTERCEPTORS,
                useFactory: authInterceptorFactory,
                multi: true,
                deps: [Injector]
            },
              .... other providers ...
    ]
    

提交回复
热议问题