When using the once method to fetch data from the Firebase database, everything works correctly. However, when I try to use the on method, I encounter an error that says: ERROR TypeError: Cannot read property 'singlePost' of null. How can I properly utilize the on method of the Firebase database to bind the data? The error occurs at { this.singlePost.content = snapshot.val();}, stating that it cannot read the value of singlePost.content because it is null.
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);
});
};
}
The code runs correctly with the following adjustments:
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);
});
};
}