将RxJS Observable转换为Promise

Dav*_*min 8 promise observable rxjs typescript angular

我正在尝试使用多个http调用将数据存储在本地存储中.我使用forkJoin等待所有调用完成,然后我想恢复我的Promise.then调用链.我该怎么做呢?

updateCache() {
    var cachesToUpdate;

    return this.fetchServerTimestamps()
        .then(res => {
            var localTimestamps = this.getLocalTimestamps();
            var serverTimestamps = this.getServerTimestamps();

            //Compare timestamps and decide which cache data types to update
            cachesToUpdate = this.cacheTypes.filter(function (cacheType) {
                return localTimestamps ? localTimestamps[cacheType.timestamp] != serverTimestamps[cacheType.timestamp] : true;
            });
        }).then(res => {
            //Request data and insert into cache
            this.fetchData(cachesToUpdate)
                .subscribe(res => {
                    res.forEach(function (item, index) {
                        this.insert(cachesToUpdate[index].messageType, JSON.stringify(item));
                    }.bind(this));
                });
        });
}

fetchData(cachesToUpdate): Observable<any> {
    return forkJoin(cachesToUpdate.map(i => this.callservice.serverRead({ path: 'api/' + i.messageType })));
}

insert(key: string, value: string, compress = true) {
    localStorage.setItem(key, compress ? LZString.compress(value) : value);
}
Run Code Online (Sandbox Code Playgroud)

And*_*ich 13

你可以使用toPromise()一种方法Observable

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/topromise.md

this.fetchData(cachesToUpdate).toPromise().then(...)
Run Code Online (Sandbox Code Playgroud)

编辑:正如FriOneLyubimov Roman在评论中提到的,不要忘记

import 'rxjs/add/operator/toPromise';
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记`import"rxjs/add/operator/toPromise";` (7认同)
  • toPromise已弃用.没有toPromise我们怎么办? (4认同)