admin管理员组

文章数量:1415145

Using Angular 4, I need to display the average of some numbers. My ponent basically looks like this:

@Component({
  selector: 'app-home',
  templateUrl: './homeponent.html'
})
export class HomeComponent {
  students:string[];
  constructor(private studentsService: StudentsService) {}
  ngOnInit() {
    this.studentsService.getStudents().subscribe(students => {
      ...
    })
    function doAvg (arr) {
      var i,
          len=arr.length,
          average=0,
          obj={};
      for (i=0;i<len;i++) {
         average += arr[i];
      }
      return (average/arr.length);
    }
  }
}

My template has this markup (GPARecord is an array of floats):

<tr *ngFor="let student of students">
  ...
  <td>{{ doAvg(student.GPARecord) }}</td>
</tr>

But I'm getting this error in the console:

ERROR TypeError: _co.doAvg is not a function

Help! Thanks!

Using Angular 4, I need to display the average of some numbers. My ponent basically looks like this:

@Component({
  selector: 'app-home',
  templateUrl: './home.ponent.html'
})
export class HomeComponent {
  students:string[];
  constructor(private studentsService: StudentsService) {}
  ngOnInit() {
    this.studentsService.getStudents().subscribe(students => {
      ...
    })
    function doAvg (arr) {
      var i,
          len=arr.length,
          average=0,
          obj={};
      for (i=0;i<len;i++) {
         average += arr[i];
      }
      return (average/arr.length);
    }
  }
}

My template has this markup (GPARecord is an array of floats):

<tr *ngFor="let student of students">
  ...
  <td>{{ doAvg(student.GPARecord) }}</td>
</tr>

But I'm getting this error in the console:

ERROR TypeError: _co.doAvg is not a function

Help! Thanks!

Share Improve this question asked Aug 31, 2017 at 5:32 jdstein1jdstein1 1172 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

(i)You do not need to have the keyword function, also with ts, use let , instead of var

(ii)Move outside of ngOnInit()

  doAvg (arr) {
          let i,
          len=arr.length,
          average=0,
          obj={};
      for (i=0;i<len;i++) {
         average += arr[i];
      }
      return (average/arr.length);
    }

You have defined your function in the ngOnInit(). And also remove function word. Move out that function like

export class HomeComponent {
  students:string[];
  constructor(private studentsService: StudentsService) {}
  ngOnInit() {
    this.studentsService.getStudents().subscribe(students => {
      ...
    });
  }

  doAvg (arr) : number {
      var i, len=arr.length, average=0,

      for (i=0;i<len;i++) {
         average += arr[i];
      }

      return (average/arr.length);
    }
}

You can also remove the obj variable from the function, because it is not used and make your function return type number.

本文标签: javascriptAngular 4 invoke method from templateStack Overflow