官方文档
创建AuthInterceptor.ts文件
import { AuthService } from './../app.service';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AppService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = this.authService.getAuthorizationToken();
if (authToken) {
const authReq = req.clone({
headers: req.headers.set('Authorization', 'bearer' + authToken),
url: environment.api_endpoint + req.url
});
return next
.handle(authReq)
.pipe(catchError(error => this.auth.handleError(error)));
}
return next.handle(req);
}
}
挂载authInterceptor.ts文件
@ngModule({
declarations: [],
imports:[],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
})
允许创建多个拦截器
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NoopInterceptor } from './noop-interceptor';
import { AuthInterceptor } from './authInterceptor';
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
];
import { httpInterceptorProviders } from './httpInterceptorProviders.ts'
@ngModule({
declarations: [],
imports:[],
providers: [ httpInterceptorProviders ]
})