将一个承诺的结果与一个观察者联系起来

时间:2017-10-02 05:45:24

标签: angular promise observable angular-promise angular-observable

如果问一个愚蠢的问题,请提前道歉。我做了搜索,但找不到我要找的答案。

我需要 index 的值,它在Promise中返回,作为参数传递给我的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();
    }
  );
}

1 个答案:

答案 0 :(得分:3)

将promise更改为observable,然后使用flatMap链接这些observable,并且可以返回一个observable。

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

或者将observable更改为promise并使用.then链接这些promise,并且你可以返回一个promise

0