1. 程式人生 > >angular4 使用HttpClient攔截器 檢查token失效,返回登入頁面

angular4 使用HttpClient攔截器 檢查token失效,返回登入頁面

1、首先建立一個攔截器服務:InterceptorService.ts
2、在app.module.ts檔案裡引入攔截器
import {InterceptorService} from ‘./InterceptorService’;
import {HTTP_INTERCEPTORS, HttpClientModule} from ‘@angular/common/http’;
接著在提供器裡宣告服務
providers: [
{provide: NZ_I18N, useValue: zh_CN},
{provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true}


],
3、InterceptorService.ts:
import {Injectable} from ‘@angular/core’;
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from ‘@angular/common/http’;
import {Observable} from ‘rxjs/internal/observable’;
import {mergeMap} from ‘rxjs/internal/operators/mergeMap’;
import {Router} from “@angular/router”;
import {NzMessageService} from “ng-zorro-antd”;

@Injectable()
export class InterceptorService implements HttpInterceptor {
constructor(private router: Router, private message: NzMessageService) {
}
intercept(req: HttpRequest, next: HttpHandler): Observable