我在 Angular 5 中使用 Observables,我从 API 获取数据。这是我的代码:
student: Student = null; // this is at a class level
ngOnInit() {
const id: number = Number(this.activatedRoute.snapshot.params['id']);
if (id) {
this.studentEditSubscription = this.studentService.getStudentById(id).subscribe(
data => {
this.student = data as Student;
console.log(this.student); // {id: 14, firstName: "A6", middleName: "C6", lastName: "B6", program: "CS"}
},
error => alert('The student you are tyring to update does not exist'));
}
console.log(this.student); // null
}
// student.service.ts
getStudentById(id: number): Observable<Object> {
return this._httpClient.get(`${this.url}/${id}`);
}
第一个 console.log(this.student)
显示正确的学生对象,而第二个似乎正在打印 null
。我使用的是 ES6 的箭头函数表示法,因此 this 必须指向该类。
我在这里缺少什么?
谢谢。
最佳答案
您在这里忽略了可观察代码异步运行。因此,第二个 console.log(...)
在第一个之前触发。这就是为什么你会得到 null
输出。您可以通过将 student
初始值更改为其他值来确认这一点。您将获得这个值。
关于javascript - Angular 5 中 Observable 中 'this' 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49638082/