猿问

为每个请求设置角集标头

为每个请求设置角集标头

我需要在用户登录后,为每个后续请求设置一些授权头。


若要为特定请求设置标头,

import {Headers} from 'angular2/http';var headers = new Headers();headers.append(headerName, value);// HTTP POST using these headersthis.http.post(url, data, {
  headers: headers})// do something with the response

参照系

但是,以这种方式手动设置每个请求的请求头是不可行的。

如何在用户登录后设置标头,并在注销时删除这些标头?


拉莫斯之舞
浏览 463回答 3
3回答

烙印99

http拦截器是现在可用通过新的HttpClient从…@angular/common/http,&nbsp;角4.3.x版本及以上.现在为每个请求添加一个头非常简单:import&nbsp;{ &nbsp;&nbsp;HttpEvent, &nbsp;&nbsp;HttpInterceptor, &nbsp;&nbsp;HttpHandler, &nbsp;&nbsp;HttpRequest, }&nbsp;from&nbsp;'@angular/common/http'; import&nbsp;{&nbsp;Observable&nbsp;}&nbsp;from&nbsp;'rxjs'; export&nbsp;class&nbsp;AddHeaderInterceptor&nbsp;implements&nbsp;HttpInterceptor&nbsp;{ &nbsp;&nbsp;intercept(req:&nbsp;HttpRequest<any>,&nbsp;next:&nbsp;HttpHandler):&nbsp;Observable<HttpEvent<any>>&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Clone&nbsp;the&nbsp;request&nbsp;to&nbsp;add&nbsp;the&nbsp;new&nbsp;header &nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;clonedRequest&nbsp;=&nbsp;req.clone({&nbsp;headers:&nbsp;req.headers.set('Authorization',&nbsp;'Bearer&nbsp;123')&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Pass&nbsp;the&nbsp;cloned&nbsp;request&nbsp;instead&nbsp;of&nbsp;the&nbsp;original&nbsp;request&nbsp;to&nbsp;the&nbsp;next&nbsp;handle &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;next.handle(clonedRequest); &nbsp;&nbsp;} }有一个不变性原则,这就是在设置新请求之前需要克隆请求的原因。由于编辑标题是一项非常常见的任务,因此实际上有一个快捷方式(同时克隆请求):const clonedRequest = req.clone({ setHeaders: { Authorization: 'Bearer 123' } });创建拦截器之后,应该使用HTTP_INTERCEPTORS提供。import&nbsp;{&nbsp;HTTP_INTERCEPTORS&nbsp;}&nbsp;from&nbsp;'@angular/common/http'; @NgModule({ &nbsp;&nbsp;providers:&nbsp;[{ &nbsp;&nbsp;&nbsp;&nbsp;provide:&nbsp;HTTP_INTERCEPTORS, &nbsp;&nbsp;&nbsp;&nbsp;useClass:&nbsp;AddHeaderInterceptor, &nbsp;&nbsp;&nbsp;&nbsp;multi:&nbsp;true, &nbsp;&nbsp;}], }) export&nbsp;class&nbsp;AppModule&nbsp;{}
随时随地看视频慕课网APP
我要回答