I'm facing a challenge while working on a review form using Firebase and Angular 4. The issue is with calculating the total length of added reviews and the sum of their ratings. Each time a new review is submitted, it gets pushed to a list of objects representing recently added reviews. I am struggling to iterate over these reviews and calculate the average rating by dividing the total sum by the number of reviews.
https://i.sstatic.net/0Z1u0.png
review.component.ts
export class ProductReviewsComponent implements OnInit {
@Input("product") product: Product;
currentRate = 8;
review = {};
reviews = {};
description;
product$;
number = [];
constructor(private reviewService: ReviewsService) {}
async ngOnInit() {
this.product$ = await this.reviewService.getReview(this.product.$key);
this.number = [];
console.log(this.number);
}
addReview() {
let review = {
rate: this.currentRate,
description: this.review
}
this.reviewService.saveReview(this.product.$key, review);
}
}
html
<form #f="ngForm">
<div class="form-group">
<ngb-rating [(rate)]="currentRate"></ngb-rating>
<textarea #description="ngModel" [(ngModel)]="review.description" name="description" type="text" class="form-control" placeholder="Dodaj opis..."
required></textarea>
<div class="alert alert-danger" *ngIf="description.touched && description.invalid">
<div *ngIf="description.errors.required">Name is required</div>
</div>
</div>
<button (click)="addReview()" class="btn btn-primary">Dodaj opinię</button>
<div *ngFor="let review of product$ | async">
{{ review.rate }} {{ review.description.description }}
</div>
</form>