TypeError: Cannot read property 'something'

2019-09-04 17:43发布

问题:

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.

回答1:

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

But for a short intro:

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

You have an html binding which depends on an employee object

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

and you request this employee object asynchronously (it will take some time to get this object) in your ngOnInit

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

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 (?)



标签: angular rxjs