首页 文章

TypeError:无法读取未定义的属性'something' . Angular 2

提问于
浏览
0

我有流行的错误,TypeError:无法读取未定义的属性'something' . 我的代码有效
但为什么我应该使用* ngIf或async?为什么会这样?
如果我没有这个奇怪的解决方案,我可以解决这个问题
对不起,但我找不到答案为什么

// service
  public getEmployee(id) {
    return this._af.database.object(`/employee/${id}`)
     .map(response => response)
     .catch(error => Observable.throw(error.json()));
  }



//component
  public employee: Employee;

  ngOnInit() {
    this.route.params
      .switchMap((params: Params) => this._EmployeesService.getEmployee(params['employeeId']))
      .subscribe(employee => {
        this.employee = employee;
      });
  }


//html
<div *ngIf="employee">...</div>` // ok
<div>{{employee?.name}}</div> // also  ok

<div>{{employee.name}}</div> // error here, TypeError: Cannot read property 'name' of undefined.

1 回答

  • 1

    我强烈建议你看看这个好答案:How do I return the response from an asynchronous call?

    但是对于简短的介绍:

    javascript的本质是异步的 . 某些功能需要一些时间才能完成 . 例如,您请求您的firebase查询数据库并为您获取结果 . 这需要一些时间,具体取决于您的网络速度 . 假设您从其他域请求某些内容,肯定需要一些时间 .

    考虑到这一点,请看一下您的示例

    你有一个html绑定,它取决于 employee 对象

    <div>{{employee.name}}</div>
    

    并在 ngOnInit 中异步请求此 employee 对象(需要一些时间来获取此对象)

    ngOnInit() {
        this.route.params
          .switchMap((params: Params) => this._EmployeesService.getEmployee(params['employeeId']))
          .subscribe(employee => {
            this.employee = employee; //<--- here 
          });
      }
    

    在将 employee 绑定到 this.employee 之前, this.employee 为空( undefined ) . 这就是为什么你用 *ngIf 或安全导航操作员( ? )进行所有 null / undefined 检查的原因

相关问题