0

I would like to return an observable from a function but I need to resolve a promise before.

async getData(path: string): Observable<Data> {
    
    // getInfo is asynchronous
    let appInfo = await App.getInfo();
    
    const headers = new HttpHeaders({'Test': appInfo.name});

    return this.http.get<Data>(environment.url + path, {headers: headers});
}

But actually this is not working because of async keyword which returns a Promise: the return of this function is Promise<Observable<data>>.

How can I get data from the asynchronous call and the return the obervable from http.get?

EDIT: this was closed linking this but I already know that an async function returns a Promise. I would like to know how to use RxJs to avoid async and therefore return an Observable.

Ernesto Schiavo
  • 1,020
  • 2
  • 12
  • 33
  • I would like to answer this question. But it's closed so I voted to reopen: In RxJS 6 and below you can call `toPromise()` if you are using RxJS 7 and above you can just `return await firstValueFrom(http.get(...))` – Some random IT boy Jan 16 '22 at 11:29
  • You can convert the promise to observable using `from`: https://rxjs.dev/api/index/function/from From that, you can `switchMap` to the http call – Maciej Kasprzak Jan 16 '22 at 11:33
  • Thanks for your responses but someone closed this without thinking on it.. Please vote to reopen – Ernesto Schiavo Jan 16 '22 at 11:34
  • You may find [this article](https://betterprogramming.pub/rxjs-patterns-emerging-from-stackoverflow-asynchronous-api-calls-as-streams-in-the-real-world-ef636c9af19a) interesting – Picci Jan 16 '22 at 17:17

0 Answers0