javascript - Angular 5 中 Observable 中 'this' 的范围

标签 javascript angular this angular5

我在 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/

相关文章:

javascript - 如何使用 $scope out restangular 函数

Javascript 作用域和点击事件

javascript - 关于 Javascript 中 'this' 关键字的困惑

jquery 多个选择器,包括 'this' - 最佳干净语法

javascript - 使用 display none 而不是 html 呈现 html

javascript - 如何在 Javascript 对象文字中命名许多事件

javascript - 有没有办法在没有文档的情况下实例化 CanvasRenderingContext2D 对象以供网络 worker 使用?

angular - ngrx 效果 : Dispatch Empty Action

javascript - 在 Javascript 中设置 cookie (Angular) : Issues with semicolon

angular - typescript 构造函数 : accept string for enum