角 – rxjs替代做Promise.resolve?

前端之家收集整理的这篇文章主要介绍了角 – rxjs替代做Promise.resolve?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个角色2服务的功能,它从api获取一些数据.第一次获取后,我希望缓存数据.我得到它这样工作:
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/fromPromise';

@Injectable()
export class ForumService {
    groups: any;

    constructor(private http: Http) {}

    getGroupDictionary() {
        var me : ForumService = this;

        if (me.groups) {
            // todo: there has to be a cleaner way ...
            return Observable.fromPromise(Promise.resolve(me.groups));
        }
        return this.http.get('/api/groups').map(res => {
            me.groups = res.json();
            return me.groups;
        });
    }
}

当数据被缓存时,我以一种愚蠢的方式返回,依赖于我从承诺中所知道的:

return Observable.fromPromise(Promise.resolve(me.groups));

这样做的正确方法是什么?

编辑:下面的anwser是对这个具体问题的有效答案,但显然有一个.cache()方法,正是我想要的:

import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class ForumService {
    groups: Observable<Groups>;

    constructor(private http: Http) {}

    getGroupDictionary(): Observable<Groups> {
        if (!this.groups) {
            this.groups = this.http.get('/api/groups').cache().map(res => res.json());
        }
        return this.groups;
    }
}
Observable.of是你正在寻找(见 this plunk):
// you might need to add this line for "Observable.of()"
import 'rxjs/add/observable/fromArray';

if (me.groups) {
  return Observable.of(me.groups);
}
原文链接:https://www.f2er.com/angularjs/142611.html

猜你在找的Angularjs相关文章