加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 将RxJS Observable转换为Promise

发布时间:2020-12-17 07:31:59 所属栏目:安全 来源:网络整理
导读:我正在尝试使用多个http调用将数据存储在本地存储中.我使用forkJoin等待所有调用完成,然后我想恢复我的Promise.then调用链.我该怎么做呢? updateCache() { var cachesToUpdate; return this.fetchServerTimestamps() .then(res = { var localTimestamps = t
我正在尝试使用多个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);
}
您可以使用Observable的toPromise()方法

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

this.fetchData(cachesToUpdate).toPromise().then(...)

编辑:作为FriOne& Lyubimov Roman在评论中提到,别忘了

import 'rxjs/add/operator/toPromise';

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读