0
在我的角度2应用程序中,我需要通过在标头中插入 令牌来验证每个请求。我有一个服务来创建请求头并插入令牌。问题是,检索令牌的方法是异步的。因此,在下面的代码中,http获得在令牌 可以插入标头之前执行。Anugalur2 - 将验证令牌注入请求标头
有没有更好的方法来强制http等待,直到令牌被发现?
代码:
getData(query: Vehicle): Observable<ResultWrapper> {
this.spinnerService.show();
return this.http
.get(`${this.myService.apiEndpoint}/vehicles?name=${query.make}`,
{ headers: this.myService.getHeaders() })
.map(this.extractData)
.catch(this.exceptionService.catchBadResponse)
.finally(() => {
this.spinnerService.hide();
});
}
为myService:
getHeaders(): any {
// this is call to an asynchronous javascript method
this.config.getToken(function (responseData) {
if (!responseData.error) {
responseData.headers.append('Authorization', "Bearer " + responseData.token);
return responseData.headers;
});
}
HTTP拦截器如何? 截取你的req之前,添加标题,然后去。 这样你的令牌相关的代码将在一个地方。 –
我在这篇文章中提到http://stackoverflow.com/questions/34464108/angular2-set-headers-for-every-request拦截器在Angular 2中不被支持。他还有一个扩展http类的例子,但是,身份验证呼叫仍然是同步的。 – noobie