Angular 2-等待服务中的数据初始化 [英] Angular 2 - Wait for data init from service

查看:243
本文介绍了Angular 2-等待服务中的数据初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有2种服务:

  • DataService-从服务器获取数据
  • CacheService-订阅 DataService 并保存映射的数据
  • DataService - gets data from the server
  • CacheService - subscribes to DataService and holds mapped data

和组件

  • ComponentA-注入CacheService并具有用于处理缓存数据的 foo函数

我的问题是-当我的 foo函数被调用时,如何确保数据完成CacheService.

My question is - How do I ensure that my CacheService is done with data when my foo function gets called.

当前解决方案,但不确定是否有更好的 Angular 2 方法.用Rx.Observables完成

Current solution that I kinda like but am not sure if there isn't some better Angular 2 way. Done with Rx.Observables

我的解决方案(简化了代码):

My solution (Code is simplified):

export class CacheService {
    myData:                IData;
    dataLoadedObservable:  Observable;
    private _emitter:      any;


    constructor(dataService: DataService){
         this.dataLoaded = Observable.create(
            e => {
            _emitter = e;
        });
    }

    private cacheData(){
         this.dataService.loadData().subscribe(data => {
             this.myData = data;
             this._emitter.next('data loaded');
        });
    }
}

ComponentA

export class ComponentA {
    this.cacheService.dataLoadedObservable.subscribe(
            isLoaded => {
                if(isLoaded === 'data loaded'){
                    // Now this.cacheService.myData is ready
                }
            }
        );
}

推荐答案

您可能应该像这样重构数据服务:

You should probably refactor your data service like this:

export class CacheService {
    private data$:Observable<IData>;

    constructor(private dataService: DataService){
        //We initialize the data Observable.
        this.data$ = new Subject();
        //We load initial data.
        this.dataService.loadData().subscribe(data => {
            //Once the data is loaded, we have to emit its value from our data$ observable.
            this.data$.next(data);
        });
    }

    //getter for our observable.
    public getData():Observable<IData>{
        return this.data$
    }

    //setter for data, hiding the observable logic behind.
    public setData(data:IData){
        this.data$.next(data);
    }
}

此重构的目标是将您的数据隐藏在可观察的后面.

The goal behind this refactor is to hide your data behind an observable.

一个简单的用法是:

cacheService.data.subscribe(data => console.log(data));

在您从订阅中释放数据之前(使用next()调用),该订阅将不会被调用,这意味着一旦实际拥有数据,订阅将被调用.

The subscription will not get called before you emit data from it (using next() call), meaning that your subscription will get called once you actually have data.

这篇关于Angular 2-等待服务中的数据初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆