0

I am working on a project in which I have to get students enrolled courses and courses list.

getting course

this.courses = <Array<Course>>[];
this.coursesService.getCourses().subscribe((response: Array<Course>) => {
this.courses = response;
console.log(this.courses);

});

getting Students enrolled course

this.id = this.router.snapshot.paramMap.get('id');
this.studentService.getStudentsById(this.id).subscribe((response: Student) => {
  this.student = response;
  console.log(this.student);
});

my code for getting avail

this.courses.forEach(function(item, i, object) {
  this.student.enrollments.forEach(function(enrollments, j , objectb) {
      if (item === enrollments) {
        object.splice(i, 1);
      }
  });
});

So when my page load. it didnt splice/remove the item in the courses which he is currently enrolled.I think the forEach function executes before it has values. is this about the subsribe? or im just doing it all wrong

buruguduys
  • 13
  • 7
  • 1
    Possible duplicate of [How to return value from function which has Observable subscription inside?](https://stackoverflow.com/questions/38291783/how-to-return-value-from-function-which-has-observable-subscription-inside) – Reactgular Dec 19 '18 at 03:05

1 Answers1

0

Since getCourses() is asynchronous, the program won't wait for the response to run the remaining code. therefore by the time, it runs the callback, it would have run the foreach code. the solution is to call the foreach inside the callback.

this.courses = <Array<Course>>[];
this.coursesService.getCourses().subscribe((response: Array<Course>) => {
this.courses = response;

this.id = this.router.snapshot.paramMap.get('id');
this.studentService.getStudentsById(this.id).subscribe((response: 
Student) => {
  this.student = response;
      this.courses.forEach(function(item, i, object) {
  this.student.enrollments.forEach(function(enrollments, j , objectb) {
      if (item === enrollments) {
        object.splice(i, 1);
      }
  });
});
});
});
VithuBati
  • 1,918
  • 1
  • 18
  • 26