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

查看:23
本文介绍了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');
        });
    }
}

组件A

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天全站免登陆