PPl在这里将其标记为重复而不是阅读此问题...链接是如何添加拦截器...我已经在做并且已经发布了代码,问题是修改要在拦截器中发送的标头
申请流程 -
登录页面 - 用户登录 - 获取一个令牌,然后在所有 http 请求中都需要发送该令牌。
工作场景
var headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('X-Token', '123'); <-- read token from storage
return this.http.post(this.url + '/' + endpoint, body, {headers: this.headers});
但问题是我必须每次都读取那个不需要的令牌,所以我修改了代码来扩展 HttpInterceptor
export class AddHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header
const clonedRequest = req.clone({ headers: req.headers.set('X-Token', 'a') });
// Pass the cloned request instead of the original request to the next handle
return next.handle(clonedRequest);
}
但问题是有谁知道,我如何在运行时添加该令牌,基本上在用户登录并获取该令牌之后,我需要更新该拦截器中的令牌。