Bridging result of a Promise to an Observable

Viewed 71

Apologies in advance if asking a dumb question. I did a search and could not find the answer I was looking for.

I need the value for index which is returned in the Promise to be passed to my Observable as an argument:

deleteFavorite(token: string, recipe: Recipe) {

const userId = this.authService.getActiveUser().uid;
let index: number;

this.indexOfFavoriteToBeRemoved(recipe)
  .then(
    index => {
      console.log(index)
    }
  );

return this.http.delete(this.databaseAddress + userId + '/' + index + '.json?auth=' + token)
  .map(
    (response: Response) => {
      return response.json();
    }
  );
}
1 Answers

Change the promise to observable then use flatMap to chain these observable, and you can return an observable.

import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/flatMap';
import 'rxjs/add/operator/map';
...
deleteFavorite(token: string, recipe: Recipe): Observable<any> {
    const userId = this.authService.getActiveUser().uid;
    return Observable.fromPromise(this.indexOfFavoriteToBeRemoved(recipe))
        .flatMap(index => this.http.delete(this.databaseAddress + userId + '/' + index + '.json?auth=' + token))
}

Or change the observable to promise and use .then to chain these promise, and you can return a promise

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
...
deleteFavorite(token: string, recipe: Recipe): Promise<any> {
    const userId = this.authService.getActiveUser().uid;
    return this.indexOfFavoriteToBeRemoved(recipe)
      .then( index => this.http.delete(this.databaseAddress + userId + '/' + index + '.json?auth=' + token)
          .map(
            (response: Response) => {
              return response.json();
            }
          ).toPromise()
      )
}
Related