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