为每个请求设置角集标头我需要在用户登录后,为每个后续请求设置一些授权头。若要为特定请求设置标头,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参照系但是,以这种方式手动设置每个请求的请求头是不可行的。如何在用户登录后设置标头,并在注销时删除这些标头?
3 回答
烙印99
TA贡献1829条经验 获得超13个赞
HttpClient@angular/common/http, 角4.3.x版本及以上.
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
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('Authorization', 'Bearer 123') });
// Pass the cloned request instead of the original request to the next handle
return next.handle(clonedRequest);
}
}const clonedRequest = req.clone({ setHeaders: { Authorization: 'Bearer 123' } });
HTTP_INTERCEPTORS
import { HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: AddHeaderInterceptor,
multi: true,
}],
})
export class AppModule {}添加回答
举报
0/150
提交
取消
