1

I am getting the error:

StudentsAttendanceCreateComponent.html:9 ERROR TypeError: Cannot read property 'insertData' of undefined at students-attendance-create.component.ts:96 at Array.forEach ()

submitForm(form: NgForm) {
let cursoID: number;

Object.keys(form.value).forEach(function (key) {
  if (key === 'cursoId') {
    cursoID = form.value[key];
  }
});

Object.keys(form.value).forEach(function (key) {
  if (key !== 'cursoId') {
    const json = {
      EstudianteId: key,
      asistencia: form.value[key],
      cursoId: cursoID
    };
    this.insertData(json);
  }
});
}



insertData(json: any) {
this.service.studentsAsistencia(json)
  .subscribe(() => {
    this.openSnackBar('Datos insertados correctamente.', 'OK');
  });
// this.clearForm();
}

Thanks !!!!

Gabriel Sule
  • 373
  • 6
  • 17

3 Answers3

1

Its reference error. If you want to use the component variable or method inside a callback, you should use lambda (arrow) function instead of using literal or anonymous function.

alokstar
  • 499
  • 2
  • 7
1

forEach takes a callback function, this is not available inside unless you bind it. One way to do it is through arrow function ()=> does bind it automatically.

Object.keys(form.value).forEach((key) => {
  if (key !== 'cursoId') {
    const json = {
      EstudianteId: key,
      asistencia: form.value[key],
      cursoId: cursoID
    };
    this.insertData(json);
  }
});
}
Aragorn
  • 5,021
  • 5
  • 26
  • 37
1

In order to use this keyword inside the callback function, you should use an arrow function, your code should look like this:

submitForm(form: NgForm) {

let cursoID: number;

Object.keys(form.value).forEach((key) => {
  if (key === 'cursoId') {
    cursoID = form.value[key];
  }
});

Object.keys(form.value).forEach((key) => {
  if (key !== 'cursoId') {
    const json = {
      EstudianteId: key,
      asistencia: form.value[key],
      cursoId: cursoID
    };
    this.insertData(json);
  }
});
}



insertData(json: any) {
this.service.studentsAsistencia(json)
  .subscribe(() => {
    this.openSnackBar('Datos insertados correctamente.', 'OK');
  });
// this.clearForm();
}

you can read about the differences in here: https://stackoverflow.com/a/34361380/7269215

Omri Grossman
  • 85
  • 2
  • 10