angular6中使用全局配置拦截器以及请求路径

直接贴代码

import { Injectable } from '@angular/core';

import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HttpResponse } from '@angular/common/http';

import { Observable } from 'rxjs/observable';

import 'rxjs/add/operator/do';

@Injectable()

export class GithubAuthInterceptor implements HttpInterceptor {

intercept (req: HttpRequest, next: HttpHandler): Observable> {

const url = ' http://192.168.1.167:8088';

const authReq = req.clone({

url: url + req.url,

headers: req.headers.set('token', localStorage.getItem('token')),

});

return next.handle(authReq).do((event: HttpEvent) => {

if (event instanceof HttpResponse) {

// do stuff with response if you want

}

}, (err: any) => {

if (err instanceof HttpErrorResponse) {

console.log(err);

if (err.status === 401) {

// redirect to the login route

// or show a modal

}

}

});

}

}

你可能感兴趣的:(angular,angular6)