httprequest之后的foreach中的空值



我正在从事一个项目,在该项目中,我必须让学生注册课程和课程列表。

获得课程

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

});

让学生注册课程

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

我的代码

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

所以当我的页面加载时。它没有在他当前正在注册的课程中拼接/删除该项目。我认为foreach功能在具有值之前执行。这是关于补贴的吗?或我只是做错了

由于getCourses()是异步的,因此程序将不等待响应运行剩余代码。因此,到时,它运行回调,它将运行foreach代码。解决方案是在回调中调用foreach。

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);
      }
  });
});
});
});

最新更新