TypeError:无法读取未定义的属性“某物".角度2 [英] TypeError: Cannot read property 'something' of undefined. Angular 2

查看:52
本文介绍了TypeError:无法读取未定义的属性“某物".角度2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常见错误,TypeError:无法读取未定义的属性某物".和我的代码有效
但是为什么我应该使用* ngIf或async?
为什么会发生?
如果没有这种奇怪的解决方案,我可以解决这个问题吗?我描述的是波纹管
对不起,我找不到答案的原因

i have popular error, TypeError: Cannot read property 'something' of undefined. and my code works
But why i should to use *ngIf or async? why it happens?
and can i solve this problem without this strange solutions what i describe bellow
Sorry but i can not find answer why

// 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.

推荐答案

我强烈建议您看一下这个好答案:

I strongly suggest you to look at this great answer: How do I return the response from an asynchronous call?

但是简短的介绍:

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

The nature of javascript is async. Some functions will take time to complete. For example you request your firebase to query the database and get a result for you. This will take some time depending on mostly your network speed. Suppose you request something from another domain, it will definitely take some time.

请牢记这一点,看看您的示例

With this in mind, take a look at your example

您有一个html绑定,该绑定取决于 employee 对象

You have an html binding which depends on an employee object

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

,您在 ngOnInit

  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 检查的原因

Before you bind employee to this.employee, this.employee is empty (undefined). That is why you do all that null/undefined checks with *ngIf or the safe navigation operator (?)

这篇关于TypeError:无法读取未定义的属性“某物".角度2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆