在调用方法之前,等待数组使用Firebase中的数据进行初始化

时间:2018-05-26 23:31:28

标签: angular typescript firebase firebase-realtime-database

我有一个Angular服务,可以访问Firebase。我有一个组件,我想从Firebase获取数据,将该信息放入一个数组,然后在现在初始化的数组上调用一些函数。我是Angular的新手,所以我不确定应该如何实现这种行为。我知道subscribe()是异步的,我需要实现我的函数,使它们对此敏感。

graph.component.ts

import { Component, OnInit, OnChanges, ViewChild, ElementRef, Input, ViewEncapsulation } from '@angular/core';
import { EscortService } from '../services/escort/escort.service';
import { Escort } from '../data/escort.data';
import * as d3 from 'd3';

@Component({
  selector: 'app-graph',
  templateUrl: './graph.component.html',
  styleUrls: ['./graph.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class GraphComponent implements OnInit {

       escortList : Escort[] = [];

        constructor(private escortService : EscortService, private element: ElementRef){
        } 

        ngOnInit(){
            this.getData();
            this.generateBarChart();
        }

        getData(){
            var esc = this.escortService.getData();
            esc.snapshotChanges().subscribe(item => {
              this.escortList = [];
              item.forEach(element => {
                    var y = element.payload.toJSON();
                    y["$key"] = element.key;
                    var currentEscort = (y as Escort);
                    if(currentEscort.status == 'Completed'){
                        console.log("escort-list -> ngOnInit() : currentEscort.status = " + currentEscort.status);
                        this.escortList.push(currentEscort);
                     }
              });
           });
        }

2 个答案:

答案 0 :(得分:1)

我也有这个问题。您需要做的是在app.component.html中的组件上放置一个*ngIf语句(或者直接在您上面的任何元素),检查变量is_loading是否等于false。您可以在服务中设置is_loading变量,在初始化时设置为true,但在收集数据后设置为false。
我希望这有帮助!

答案 1 :(得分:1)

escortList应该是Observable。

    private const escortList = new ReplaySubject<Escort[]>();
    get escortList() : Observable<Escort[]> {
        return this.escortList.asObservable();    // this prevents caller from being able to call method 'next' on the subject
    }

    constructor(private escortService : EscortService, private element: ElementRef){
    } 

    ngOnInit(){
        this.getData();
        this.generateBarChart();
    }

    getData(){
        var esc = this.escortService.getData();
        esc.snapshotChanges().subscribe(item => {
          const newEscortList = [];
          item.forEach(element => {
                var y = element.payload.toJSON();
                y["$key"] = element.key;
                var currentEscort = (y as Escort);
                if(currentEscort.status == 'Completed'){
                    console.log("escort-list -> ngOnInit() : currentEscort.status = " + currentEscort.status);
                    newEscortList.push(currentEscort);
                 }
          });
          this.escortList.next(newEscortList);
       });
    }

然后,在您的组件中,您只需订阅Observable即可获取更新。别忘了取消订阅。