2017-08-25 50 views
2

我需要發送標題給我的HttpRequest。Angular 4.3 HttpClient - 如何正確使用HttpHeaders和攔截器?

我已經在這裏搜索,我已經嘗試了一些我找到的答案,但沒有一個人工作。

標題不會被髮送到API,如果我檢查clonedRequest對象,它不會顯示標題。這是我的代碼:

public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    // Clone the request to add the new header. 
    const clonedRequest = req.clone(); 

    clonedRequest.headers.set("ModuleId", this.dnnContext.moduleId); 
    clonedRequest.headers.set("TabId", this.dnnContext.tabId); 

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

enter image description here

我缺少什麼?

回答

1

我都面臨着類似的問題&想通了你的第二(類型錯誤:CreateListFromArrayLike呼籲非對象)的問題,對於一些 原因,如果你通過號碼類型(它具有類型檢查,但如果VAR類型是any它允許&它的情況對我來說)在頭部(ModuleId或你的情況TabId值),它拋出這個錯誤,所以你可以 將其轉換爲字符串,而通過這樣的:

const authReq = req.clone({ 
    headers: req.headers.set('ModuleId', this.dnnContext.moduleId.toString()).set('TabId', this.dnnContext.tabId.toString()) 
}); 
// Pass on the cloned request instead of the original request. 
return next.handle(authReq); 

也回覆了你的github issue

1

那是因爲來自新的HttpClient模塊的類的實例是不可變的。所以你需要重新分配你變異的所有屬性。這轉化爲你的情況如下:

public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    // Clone the request to add the new header. 
    const headers = req.headers.set("ModuleId", this.dnnContext.moduleId).set("TabId", this.dnnContext.tabId); 
    const clonedRequest= red.clone({ 
    headers: headers 
    }); 

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

謝謝。現在我收到以下錯誤:TypeError:CreateListFromArrayLike在非對象上調用 – DAG

+0

我想說,錯誤不會以任何方式與http客戶端相關.... –

+0

我在遷移之前沒有發生此錯誤,無論如何我認爲這與標題無關(我希望)...無論如何,感謝 – DAG