具有角度2的可观察数据流的流式(实时)数据

时间:2017-01-19 15:17:08

标签: javascript angular observable ngrx

我正在构建一个从API加载数据的仪表板,我们没有实时数据流,因此我们的解决方案是让http获取所有10秒。 我们的问题是仪表板开始工作非常缓慢,难以点击。

我想知道在没有打扰应用程序运行的情况下制作它的最佳方法是什么。 我们还使用ngrx / store来更新仪表板中的数据。 以下是代码片段:

timer$: Observable<number> = Observable.timer(0, 10000);
loadBlocksPlantings(reload: boolean = false) {
    if (this.loaderFields$ && !reload) {
      return;
    }
    let numberLoads: number = 0;
    console.log(`FieldsService.loadBlocksPlantings() firstTime... (${new Date()})`);
    this.loaderFields$ = this.timer$.switchMap((time: number) => {
     return Observable.forkJoin(
        [
          this.blocksService.loadBlocksObservable(),
          this.plantingsService.loadPlantingsObservable()
         ]
       );
    })
    .subscribe(
      ([blocks, plantings]: [Block[], Planting[]]) => {
        console.log(`FieldsService.loadBlocksPlantings() loading... (${new Date()})`);
        let blockMap: Map<string, Block> = Map<string, Block>();
        let plantingsMap: Map<string, Planting> = Map<string, Planting>();
        blocks.forEach((block: Block) => {
          blockMap = blockMap.set(block._id, block);
        });
        plantings.forEach((planting: Planting) => {
          plantingsMap = plantingsMap.set(planting._id, planting);
        });
        // Here if already load once next time only update part of the data
        if (numberLoads > 0) {
           this.store.dispatch({type: PLANTINGS_ACTIONS.RELOAD_PLANTINGS, payload: plantingsMap});
           numberLoads++;
           return;
        }
        this.store.dispatch({type: BLOCKS_ACTIONS.ADD_BLOCKS, payload: blockMap});
        this.store.dispatch({
          type: POLYGONS_ACTIONS.ADD_POLYGONS, payload: {
            blocks: blockMap,
            plantings: plantingsMap
          }
        });
        this.store.dispatch({type: PLANTINGS_ACTIONS.ADD_PLANTINGS, payload: plantingsMap});
        numberLoads++;
        this.store.dispatch({type: LOADER_ACTIONS.LOADED});
      }
    );
  }

0 个答案:

没有答案