[英]How to write an async/await method as an Observable in Angular?
I used to do async/await and just learned to use Observable in Angular because it's the Angular way, so I want to refactor this code snippet here to make this as an Observable:我曾经做 async/await 并且刚刚学会在 Angular 中使用 Observable,因为它是 Angular 方式,所以我想在这里重构这个代码片段以使其成为一个 Observable:
async refreshToken() {
const headers = this.authStorage.getRequestHeader();
const body = {
refreshToken: this.authStorage.getStoredValue('refreshToken'),
};
const newAccessToken = await this.http
.post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers })
.toPromise();
this.authStorage.setValueToStore('accessToken', newAccessToken);
}
So basically I am making a post request to my backend and get a token back and then use it in the authStorage.所以基本上我正在向我的后端发出一个发布请求并取回一个令牌,然后在 authStorage 中使用它。
I tried to do this as an Observable and got this so far:我尝试将其作为 Observable 执行此操作,并且到目前为止:
refreshToken(): Observable<any> {
const headers = this.authStorage.getRequestHeader();
const body = {
refreshToken: this.authStorage.getStoredValue('refreshToken'),
};
return this.http
.post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers });
this.authStorage.setValueToStore('accessToken', newAccessToken);
}
This is okay and works but I cannot call my authStorage this way.这没关系并且有效,但我不能以这种方式调用我的 authStorage。 I cannot save it in a variable because an Observable needs to have a return... I also tried with pipe and subscribe but no chance.
我无法将它保存在变量中,因为 Observable 需要返回......我也尝试使用 pipe 并订阅但没有机会。
Any tips?有小费吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.