亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為每個請求設置角集標頭

為每個請求設置角集標頭

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

http攔截器是現在可用通過新的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 {}


查看完整回答
反對 回復 2019-06-28
  • 3 回答
  • 0 關注
  • 501 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號