3

如果问一个愚蠢的问题,请提前道歉。我进行了搜索,但找不到我正在寻找的答案。

我需要将Promise 中返回的index值作为参数传递给我的 Observable:

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();
    }
  );
}
4

1 回答 1

3

将 promise 更改为 observable,然后使用 flatMap 链接这些 observable,您可以返回一个 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))
}

或者将 observable 更改为 promise 并使用 .then 链接这些 promise,您可以返回一个 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()
      )
}
于 2017-10-02T05:57:59.450 回答