1

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 return cannot read property fullName of undifined

<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

4

1 回答 1

1

您可以按如下方式更改它,以这种方式创建的订阅更少,除非用户经过身份验证,否则 div 块将不会显示在 DOM 中,安全操作员是安全检查讨厌属性的方法:

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

或保持如下:

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

虽然我也建议检查为什么user没有为经过身份验证的用户填充属性

于 2020-04-29T11:13:52.400 回答