為每個請求設置角集標頭我需要在用戶登錄后,為每個后續請求設置一些授權頭。若要為特定請求設置標頭,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
提交
取消