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

前端 未结 3 883
长发绾君心
长发绾君心 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条回答
  •  甜味超标
    2020-12-25 15:06

    the above @bryan60 answer is works fine , if any one facing issue like me with catch the error in below line

    return next.handle(authReq).catch(x=> this.handleAuthError(x));
    

    using do() handle the error(if you face issue with catch())

    import in file:

    import 'rxjs/add/operator/do';
    

    handle error:

    return next.handle(authReq)
     .do(
        success => {/*todo*/},
        err => {this.handleAuthError(authReq)}
        );
    }
    
    handleAuthError(err: any) {
        if(err.status === 401 || err.status === 403) {
        this.storageService.clear();
        window.location.href = '/home';
        }
    }
    

    I hope this is help someone.

提交回复
热议问题