答案 0 :(得分:0)
我认为您不需要外部库即可。
您应该看一下拦截器的概念:https://angular.io/api/common/http/HttpInterceptor
一个例子:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private localStorage: LocalStorageService, private sessionStorage: SessionStorageService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.localStorage.retrieve('authenticationToken') || this.sessionStorage.retrieve('authenticationToken');
if (!!token) {
request = request.clone({
setHeaders: {
Authorization: 'Bearer ' + token
}
});
}
return next.handle(request);
}
}