简体   繁体   中英

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 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.

I tried to do this as an Observable and got this so far:

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. 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.

Any tips?

You can perform your side-effect logic inside the tap operator:

return this.http
    .post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers })
    .pipe(
        tap(newAccessToken => this.authStorage.setValueToStore('accessToken', newAccessToken))
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM