【发布时间】:2020-04-18 11:20:41
【问题描述】:
我正在从 Angular 服务调用安全的 REST API。在这种情况下,我必须在调用任何 API 之前获取一次令牌,并将其作为 HTTP Header 的一部分传递。但是,当我从我的组件中调用任何函数时,我将 app_token 设为未定义。这是由于对 token_api 的异步调用。下一个调用成功,因为之前的调用从服务器获取令牌的值。
我已经在 get_token 函数中添加了 async-await,但徒劳无功.. 关于如何处理这种情况的任何建议。
private app_token;
private getToken(){
if (this.token == undefined) {
console.log("getting new token");
return this.httpClient.post<Token>(this.TOKEN_API, body, options)
.pipe(retry(3), catchError(this.handleError))
.subscribe(data => {
console.log(data[0].username);
return this.app_token = data;
});
}
}
public getEmployee{
this.getToken();
const headers = new HttpHeaders()
.set('Authorization', 'Bearer ' + this.app_token );
const options = {
headers: headers
};
return this.httpClient.get(this.EMP_API, options)
.pipe(retry(3), catchError(this.handleError));
}
public getDepartments{
this.getToken();
const headers = new HttpHeaders()
.set('Authorization', 'Bearer ' + this.app_token );
const options = {
headers: headers
};
return this.httpClient.get(this.DEPT_API, options)
.pipe(retry(3), catchError(this.handleError));
}
【问题讨论】:
标签: angular httpclient angular-httpclient