【问题标题】:Angular 2 - Wait for data init from serviceAngular 2 - 等待来自服务的数据初始化
【发布时间】:2023-03-30 13:07:01
【问题描述】:

有 2 种服务:

  • DataService - 从服务器获取数据
  • CacheService - 订阅 DataService 并保存映射数据

和组件

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

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

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

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

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
                }
            }
        );
}

【问题讨论】:

    标签: angular lazy-loading observable angular2-services angular-services


    【解决方案1】:

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

    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);
        }
    }
    

    此重构背后的目标是将您的数据隐藏在 observable 后面。

    一个简单的用法是:

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

    在您从中发出数据之前不会调用订阅(使用next() 调用),这意味着一旦您实际拥有数据,您的订阅就会被调用。

    【讨论】:

    • 由于 typescript 不允许我使用不同类型的 getter 和 setter,我不得不使用 Union 类型。 type DataObservable = Observable&lt;IData&gt; | IData;public get data(): DataObservable{...} public set data(value: DataObservable){...}只想提一下。
    • @Xquick 哦,我不知道,从不诚实(我的意思是不同类型的 getter 和 setter)
    • 因此使用联合类型毫无价值,因为我必须对 getter 的每次使用进行类型保护。所以我只留下了 data$ 的 getter,删除了 setter 并拥有 setData 函数,就像你回答的那样。现在工作正常,谢谢
    猜你喜欢
    • 2019-04-23
    • 2016-07-27
    • 2019-03-27
    • 2021-11-08
    • 2016-07-23
    • 1970-01-01
    • 2020-03-25
    • 2015-09-15
    • 1970-01-01
    相关资源
    最近更新 更多