Search code examples
angularangular-httpclient

Angular httpClient cannot read property undefined of undefined


I have an Object which makes up the content of my nav. The object is obtained with a get() request, which sits inside the ngOnInit() function of the navigation component. With the following code, the navigation functions appears to work fine:

this.httpClient.get(this.url).pipe(map(res => res)).subscribe(res => this.menu = res);

However the console is displaying an error:

ERROR TypeError: Cannot read property 'undefined' of undefined

The error references a line in the associated HTML: *ngIf="menu[category]" but I guess for a fraction of a second, and at the point in time the HTML is rendered, the menu object does not exist so I see this error. Am I doing something wrong here? I must be.


Solution

  • You're right. The template renders before the menu property is initialized and so it throws an error.

    There are multiple ways to solve this.

    1. Wrap the template in a *ngIf check.
    <ng-container *ngIf="!!menu">
      <div *ngIf="menu?.category">
        ...
      </div>
    </ng-container>
    
    1. Use safe navigation operator
    <div *ngIf="menu?.category">
      ...
    </div>
    
    1. Using async pipe. This would also remove the overhead of handling a subscription in the controller.

    Controller (*.ts)

    export class SomeComponent implements OnInit {
      menu$: Observable<any>;
    
      ngOnInit() {
        this.menu$ = this.httpClient.get(this.url);
      }
    }
    

    Template (*.html)

    <ng-container *ngIf="(menu$ | async) as menu">
      <div *ngIf="menu.category">
        ...
      </div>
    </ng-container>