我在Angular2中使用Firebase来获取对象。
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");
}
});
});
}
}
我在模板中约束fireObj
:
<p>{{ (fireObj | async)?.title }}</p>
一切正常,但有时控制台正在记录data
(比如1秒后),但dom /模板在5-10秒后会更新。
这种行为有什么特别原因吗?
答案 0 :(得分:0)
我通过明确调用run()
的{{1}}方法解决了这个问题。
ngZone
我知道这不是最好的解决方案,但我确保this.fireObj.subscribe(data => {
// some other code.
this._ngZone.run(() => {});
});
只被调用一次(即在第一次回调期间),因为Angular正常绑定它。
感谢@SyntacticFructose指导我正确的方向。