使用一次方法正确地从firebase数据库中获取数据。但是使用on方法,它显示错误ERROR TypeError:无法读取null的属性'singlePost'。如何在firebase数据库的方法上使用并绑定数据?我在{this.singlePost.content = snapshot.val();}得到错误,说无法读取null的singlePost.content的值。
export class BlogDetailComponent implements OnInit {
singlePost: Blog;
id: any;
constructor(private route: ActivatedRoute, private router: Router) {
let contentUpdated: any;
}
ngOnInit() {
let postId = this.route.snapshot.params['id'];
this.getSingle(postId);
this.id = postId;
let starCountRef = firebase.database().ref('blogPosts/' + this.id + '/content');
starCountRef.on('value', function (snapshot) {
if (snapshot.val() != null) {
this.singlePost.content = snapshot.val();
}
});
}
getSingle(id: string) {
let dbRef = firebase.database().ref('blogPosts');
dbRef.orderByChild('id')
.equalTo(id)
.once('value')
.then((snapshot) => {
let tmp = snapshot.val();
let transform = Object.keys(tmp).map(key => tmp[key]);
let title = transform[0].title;
let content = transform[0].content;
let imgTitle = transform[0].imgTitle;
let img = transform[0].img;
this.singlePost = new Blog(title, content, imgTitle, img);
});
};
}
如果我运行以下代码,则有效。
export class BlogDetailComponent implements OnInit{
singlePost : Blog;
id : any;
constructor(private route : ActivatedRoute, private router : Router) {
let contentUpdated : any;
}
ngOnInit() {
let postId = this.route.snapshot.params['id'];
this.getSingle(postId);
this.id = postId;
let starCountRef = firebase.database().ref('blogPosts/'+this.id+'/content');
starCountRef.on('value',function(snapshot){
if(snapshot.val() != null )
{ console.log(snapshot.val());}
});
}
getSingle(id : string){
let dbRef = firebase.database().ref('blogPosts');
dbRef.orderByChild('id')
.equalTo(id)
.once('value')
.then((snapshot) => {
let tmp = snapshot.val();
let transform = Object.keys(tmp).map(key => tmp[key]);
let title = transform[0].title;
let content = transform[0].content;
let imgTitle = transform[0].imgTitle;
let img = transform[0].img;
this.singlePost = new Blog(title,content,imgTitle,img);
});
};
}
您应该使用Arrow function
/ Lamba
来获取回调函数中正确的this
(上下文)
starCountRef.on('value',(snapshot: any) => {
if(snapshot.val() != null ) {
this.singlePost = {content : snapshot.val() };
};
});