1,創建一個ts文件;
2,base-interceptor.ts;寫入代碼:
import { Injectable } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from "@angular/common/http";
import { PublicService } from "../public/public.service";
import { throwError } from 'rxjs';
import { catchError, retry } from "rxjs/operators";
import * as Cookies from 'js-cookie';
@Injectable()
export class BaseInterceptor implements HttpInterceptor {
public erors;
constructor(public router: Router, public url: PublicService) {}
intercept(req, next: HttpHandler) {
let hadBaseurl = Boolean(req.headers.get('hadBaseurl')) || false;
let newReq = req.clone({
url: hadBaseurl ? `${req.url}` : `${baseurl}${req.url}`,
});
let Cookie = Cookies.get('manageAuthorizationData');
if (!req.cancelToken) {
newReq.headers =
newReq.headers.set('Authorization', 'Bearer '+Cookie);
}
return next.handle(newReq)
.pipe(
retry(2),
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
/*console.log(error);*/
this.erors = error;
if (this.erors.error.Message == '已拒絕為此請求授權。') {
localStorage.setItem('quan', 'true');
window.location.href = '#/Login';
}
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
}
3,index.ts中引入base-interceptor.ts;
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { BaseInterceptor } from './base-interceptor';
/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: BaseInterceptor, multi: true },
];
2,在app.module.ts引入,都可以用了;