Rohit Arya Rohit Arya - 15 days ago 5
TypeScript Question

Async data binding in Angular2 taking time even after data is loaded

I am using Firebase in Angular2 to fetch an object.

import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseObjectObservable } from 'angularfire2';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

fireObj: FirebaseObjectObservable<any>;

constructor(private af: AngularFire, private route: ActivatedRoute) {

}

ngOnInit() {

this.route.params.forEach((params: Params) => {
let id = params['id'];

this.fireObj = this.af.database.object("/path/" + id);

this.fireObj.subscribe(data => {
if(data.$value !== null) {
console.log(data);
}else {
console.log("failed");
}
});

});
}
}


And I am binding
fireObj
in the template:

<p>{{ (fireObj | async)?.title }}</p>


Everything works fine as expected, but sometimes console is logging
data
(say after 1 second) but dom/template is getting updated after 5-10 seconds.

Is there any particular reason for this behavior?

Answer

I solved it by explicitly calling run() method of ngZone.

this.fireObj.subscribe(data => {
    // some other code.
    this._ngZone.run(() => {});
});

I know this is not the best solution, but I have made sure that _ngZone.run() is called only once (that is during the first callback) as after that Angular is binding to it normally.

Thanks to @SyntacticFructose for guiding me in the correct direction.

Comments