gpt4 book ai didi

angular - Promise 与 Observable 的桥接结果

转载 作者:太空狗 更新时间:2023-10-29 18:24:53 26 4
gpt4 key购买 nike

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

我需要将 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();
}
);
}

最佳答案

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

关于angular - Promise 与 Observable 的桥接结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46520076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com