[英]Use Object.keys() instead of .length on Firebase Object
如何使用 Object.keys() 来纠正这个片段? 当评论 id 是数字时,代码可以正常工作。 现在如何使它与来自 firebase 的自动生成的 ID 一起工作。
(数据结构如下)
ngOnInit() { this.route.params.pipe(switchMap((params: Params) => this.dishservice.getDish(params['id']))).subscribe(dish => { this.dish = dish this.favorite = this.favoriteService.isFavorite(this.dish.id); //compute the average of ratings and render the number of comments this.numcomments = this.dish.comments.length; let total =0; this.dish.comments.forEach(comment =>total += comment.rating); this.avgstars = (total/this.numcomments).toFixed(2); }, errmess => this.errMess = <any>errmess); }
尝试这个
const commentIds = Object.keys(this.dish.comments);
this.numcomments = commentIds.length;
let total = 0;
commentIds.forEach(commentId => total += this.dish.comments[commentId].rating);
this.avgstars = (total/this.numcomments).toFixed(2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.