0

I have an object UserScore. It has field called score that is an number. I am keeping all userscores in userScores variable and overallScore for average of scores.

public userScores: any = [];
public overallScore : number = 0;

I tried so far something like this:

   sumRatingValues(): void{
    let i = 0;
    this.userScores.forEach((score: any) => {
      this.overallScore += score.score;
      i++;
      console.log(this.overallScore);
    });
    this.overallScore / i;
  }

Then I am using this method in ngOnInit.

But it doesn't print to conole log anything and overallScore value is 0.

EDIT How I fetch data:

getRating(){
    this.route.params
    .subscribe((params: Params) => {
      const id = params['id'];
      this.sharedService.getRecipesScoresForRecipe(id).subscribe(scores =>{
        this.userScores = scores;
        console.log(this.userScores)
      })
  });
  }

console.log prints out properly objects with their fields and value enter image description here And my ngOnInit:

ngOnInit(): void {
    ...
    this.getRating();
    this.sumRatingValues();
}

Little testing on front:

<div class="class" *ngFor="let user of userScores">{{user.score}} - {{overallScore}}</div>

This is how it look like: result

Taxyy
  • 33
  • 4

0 Answers0