Javascript 错误类型错误:无法读取属性';单柱&x27;角5中的空值
使用once方法从firebase数据库正确获取数据的代码。但对于on方法,它显示error-TypeError:无法读取null的属性“singlePost”的错误。如何在firebase数据库和绑定数据的方法上使用?我在{this.singlePost.content=snapshot.val();}处遇到错误,表示无法读取null的singlePost.content的值Javascript 错误类型错误:无法读取属性';单柱&x27;角5中的空值,javascript,angular,typescript,firebase,Javascript,Angular,Typescript,Firebase,使用once方法从firebase数据库正确获取数据的代码。但对于on方法,它显示error-TypeError:无法读取null的属性“singlePost”的错误。如何在firebase数据库和绑定数据的方法上使用?我在{this.singlePost.content=snapshot.val();}处遇到错误,表示无法读取null的singlePost.content的值 export class BlogDetailComponent implements OnInit { sin
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);
});
};
}
您应该使用
箭头函数
/Lamba
在回调函数中获得正确的此
(上下文)
starCountRef.on('value',(snapshot: any) => {
if(snapshot.val() != null ) {
this.singlePost = {content : snapshot.val() };
};
});
谢谢,先生。现在,我有一个错误,说无法读取的属性“内容”的不可定义的可能的副本