首页 > 解决方案 > 如何知道 observable 中的数据何时可以在 Angular 2+ 中使用?

问题描述

当我发现很难编写一个使用将由我的服务初始化和更新的变量的函数时,我正在尝试使用 Angular 4 和 NodeJS 编写一个小型 Web 应用程序。这是我的片段:

getStudentsBySessionId() {
  this.sessionService
    .getStudentsBySession(this._sessionId)
    .subscribe(students => {
      this.sessionStudents = students;
      this.reInitDatatable();
  });
}

isAdded(studentId){
  this.sessionStudents.forEach(student => {
    if(student._id === studentId){
      return true;
    }
  });
  return false;
}

但是,在模板文件中调用 isAdded 函数时,会出现 sessionStudents 的 undefined 错误。

在这种情况下如何正确编写程序?

谢谢!

标签: angular

解决方案


将 sessionStudents 初始化为一个空数组怎么样?然后我相信模板文件中的函数调用会起作用。假设以下是您的组件...

class YourComponent {

  sessionStudents = [];

  getStudentsBySessionId() {
    this.sessionService
      .getStudentsBySession(this._sessionId)
      .subscribe(students => {
        this.sessionStudents = students;
        ...
      });
  }

  isAdded(studentId){
    ...
  }

}

我相信当 sessionStudents 的值在订阅的成功处理程序中重新分配时,模板应该会自动接受更改。

这有帮助吗?


推荐阅读