import { Injectable , Injector } from '@angular/core' ; import { HttpInterceptor , HttpRequest , HttpHandler , HttpEvent , HttpResponseBase , HttpErrorResponse } from '@angular/common/http' ; import { Observable , throwError , of } from 'rxjs' ; import { mergeMap , catchError } from 'rxjs/operators' ; import { Router } from '@angular/router' ; import { LocalStorageService } from './local-storage.service' ; @ Injectable ( ) export class HttpInterceptorService implements HttpInterceptor { constructor ( private injector ) { } private goTo ( url ) { setTimeout ( ( ) => this . injector . get ( Router ) . navigateByUrl ( url ) ) ; } private checkStatus ( ev ) { if ( ev . status >= 200 && ev . status < 300 ) { return ; } } private handleData ( ev ) { this . checkStatus ( ev ) ; switch ( ev . status ) { case 200 : break ; case 401 : const ls = this . injector . get ( LocalStorageService ) ; ls . clearAll ( ) ; this . goTo ( '/' ) ; case 403 : case 404 : case 500 : this . goTo ( `/exception/${ ev . status }` ) ; break ; default : if ( ev instanceof HttpErrorResponse ) { console . warn ( '未可知错误，大部分是由于后端不支持CORS或无效配置引起' , ev ) ; return throwError ( ev ) ; } break ; } return of ( ev ) ; } intercept ( req , next ) { const url = req . url ; if ( ! url . startsWith ( 'https://' ) && ! url . startsWith ( 'http://' ) ) { } let newReq = null ; const localStorageService = this . injector . get ( LocalStorageService ) ; const accessToken = localStorageService . get ( 'x-access-token' ) ; newReq = req . clone ( { setHeaders : { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' , 'x-access-token' : accessToken ? accessToken : '' } } ) ; return next . handle ( newReq ) . pipe ( mergeMap ( ( event ) => { if ( event instanceof HttpResponseBase ) { return this . handleData ( event ) ; } return of ( event ) ; } ) , catchError ( ( err ) => this . handleData ( err ) ) ) ; } }