我正在从firebase获取数据,我希望组件视图应该在数据可用时更新,但更新视图上的数据需要的时间超过15 sec。下面是我的组件和模板代码。
在我的例子中,数据可用性和视图绑定之间存在一些延迟,为什么?或者如何通知Angular更新数据以便立即更新视图?

@Component({
    ...
})
export class BoardComponent implements OnInit {
    private db: firebase.database.Database;
    public boards: Array<any>;


    constructor(private route: ActivatedRoute,
        private authService: AuthService) {
        this.db = firebase.database();
        this.boards = new Array<any>();

    }


    ngOnInit() {
        this.loadBoards();
    }

    loadBoards() {
        var ref = this.db.ref('/boards');

        ref.on('child_added', (child) => {
            console.log("Question added! adding data one by one");
            var obj = child.val();
            obj.key = child.key;
            this.boards.push(obj);
        });
    }
}

模板:
...

<tr *ngFor="let item of boards">
    <td>{{item.name}}</td>

</tr>

...

最佳答案

您需要使用NgZone,因为firebase.database.Database更新发生在角度区域之外,并且不会触发更改检测:

 constructor(private zone: NgZone, private route: ActivatedRoute,

 loadBoards() {
    ...
    ref.on('child_added', (child) => { NgZone.run(()=> {var obj = child.val();..

09-19 19:47