2017-09-26 101 views
1

我寫了一個角(4.3.6)HttpInterceptor來添加一些標題字段,但如果我在調試器中檢查它們,標題不會更新。任何想法?Angular HttpInterceptor不會更改標題

import {Injectable} from '@angular/core'; 
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; 
import {Observable} from 'rxjs/Observable'; 

@Injectable() 
export class AuthInterceptor implements HttpInterceptor { 


    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 

     console.log('AuthInterceptor at work'); 

     const contentTypeReq = req.clone({ 
      headers: req.headers.set('Content-Type', 'application/json') 
     }); 

     const token = localStorage.getItem('token'); 
     if (token) { 
      const authReq = contentTypeReq.clone({ 
       headers: req.headers.set('Authorization', 'Bearer ' + token) 
      }); 
      return next.handle(authReq); 
     } 

     // Pass on the cloned request instead of the original request. 
     return next.handle(contentTypeReq); 
    } 
} 
+0

設置內容類型是沒用的。 Angular爲你做到了這一點。你使用調試器運行你的代碼嗎?或者只是添加console.log()來檢查令牌是否已設置? –

+0

是的 - 我在調試器中運行它,看到它的beeing叫。但標題不更新。請參閱https://angular.io/guide/http#setting-new-headers – netshark1000

回答

0

他們很懶。例如keys method樣子:

keys(): string[] { 
    this.init(); <== initialize 

    return Array.from(this.normalizedNames.values()); 
} 

如果要檢查他們只要致電:

req.headers.keys() 

如果你想檢查值,您可以使用getgetAll方法:

req.headers.getAll('Content-Type') 

或者您可以從控制檯調用init方法,然後您將能夠在headers地圖

enter image description here

ê頭而且當angular adds headers to request它使用forEach方法調用init方法了。

+0

我們是否可以更新這些標頭......例如在請求我發送''x-auth-token''並且如果發生401,那麼我想要更新標題..是否有可能?更多信息參考:[https://stackoverflow.com/questions/48200491/request-header-is-not-updated-successfully-from-interceptor-angular-2-4-401-han] –