angularobservableundefinedasync-pipe

Cannot read property of undefined on data loading


authState$ is an observable variable of type

{
    ...
    isAuthenticated: boolean;
    user: User | null;
}

User property is initiated on ngrx effect init if the user is authenticated.

The error is that the code below in template returns

Cannot read property fullName of undefined

<div *ngIf="(this.authState$ | async).isAuthenticated" >
    {{ (this.authState$ | async).user.fullName || '' }}
</div>

I tried this solution

{{ (this.authState$ | async).user ? (this.authState$ | async).user.fullName : '' }}

but it turned out that it doesn't listening for changes and I have to reload the page


Solution

  • You can change it as follows, fewer subscription created this way and div block will not be shows in DOM unless user is authenticated, safe operator is the way to get safely check nasty properties:

    <ng-container *ngIf="authState$ | async as authState">
      <div *ngIf="authState?.isAuthenticated" >
        {{ authState?.user?.fullName || '' }}
      </div>
    </ng-container>
    

    or keep it as follows:

    <div *ngIf="(this.authState$ | async)?.isAuthenticated" >
        {{ (this.authState$ | async)?.user?.fullName || '' }}
    </div>
    

    Although I would also recommend to check why user property is not populated for authenticated users