gpt4 book ai didi

javascript - 错误类型错误 : Cannot read property 'singlePost' of null in angular 5

转载 作者:行者123 更新时间:2023-11-30 20:42:37 24 4
gpt4 key购买 nike

使用一次方法正确地从 firebase 数据库中获取数据的代码。但是使用 on 方法它显示错误 ERROR TypeError: Cannot read property 'singlePost' of null。如何使用 firebase 数据库的方法并绑定(bind)数据?我在 {this.singlePost.content = snapshot.val();} 处遇到错误,说无法读取 singlePost.content 的值为 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);
});
};
}

如果我运行以下代码就可以工作。

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(context)

starCountRef.on('value',(snapshot: any) => {
if(snapshot.val() != null ) {
this.singlePost = {content : snapshot.val() };
};
});

关于javascript - 错误类型错误 : Cannot read property 'singlePost' of null in angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49084251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com