angular - 如何知道 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 错误。
在这种情况下如何正确编写程序?
谢谢!
解决方案
将 sessionStudents 初始化为一个空数组怎么样?然后我相信模板文件中的函数调用会起作用。假设以下是您的组件...
class YourComponent {
sessionStudents = [];
getStudentsBySessionId() {
this.sessionService
.getStudentsBySession(this._sessionId)
.subscribe(students => {
this.sessionStudents = students;
...
});
}
isAdded(studentId){
...
}
}
我相信当 sessionStudents 的值在订阅的成功处理程序中重新分配时,模板应该会自动接受更改。
这有帮助吗?
推荐阅读
- python - 比较对应的列并将结果存储在新列中
- python - 如何让 dag 获取调度实例的序列号(例如每周调度程序的 1、2、3、4)
- python-3.x - 使用参数 b'' 调用了纯 python 回调函数,丢失了 cython 函数中的实际数据
- java - Apache poi如何通过密码取消隐藏工作表?
- android - Trace_MediaProvider.csv 是什么?
- javascript - 如何使用reactjs组件仅选择组中的一个复选框
- wordpress - 如何使用 Wordpress - divi 将 2 列与垂直线分开?
- android - 我无法通过改造获得回应
- android - 在华为 P20 上在 Textureview 上绘图时出现的问题
- angular - Angular 单元测试路由卡在根目录上,而不是在 redirectTo 中定义的路由