2017-08-25 82 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

相关问题