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?

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.