Simon
Simon

Reputation: 21

Using observable in template freezes browser

Using auth.appUser$ in component.html causes the browser to freeze. However, subscribing to auth.appUser$ in component.ts correctly outputs the information to the console.

Note that appUser$ has type: Observable<AppUser>, where AppUser was defined in an interface with the fields name, email, and isAdmin.

The console does not output any exceptions.

navbar.component.html: (the browser freezes here!)

<li *ngIf="auth.appUser$ | async as user; else anonymousUser" ngbDropdown class="nav-item dropdown">
    <a ngbDropdownToggle class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      {{ user.name }}
    </a>
</li>

navbar.component.ts: (the browser does not freeze!)

export class NavbarComponent implements OnInit {

    constructor(public auth: AuthService) {
        this.auth.appUser$.subscribe(user => console.log(user.name));
    }
}

auth.appUser$ is an observable defined in auth.service.ts:

export class AuthService {

  user$: Observable<firebase.User>;

constructor(
    private userService: UserService) {
    this.user$ = this.afAuth.authState;
  }

get appUser$(): Observable<AppUser> {
    return this.user$
      .pipe(
        switchMap(user => this.userService.get(user.uid).valueChanges())
      );
  }
}

Upvotes: 2

Views: 602

Answers (1)

Sheik Althaf
Sheik Althaf

Reputation: 1605

Please try to warp the async in braces

*ngIf="(auth.appUser$ | async) as user; else anonymousUser"

Alternative

<ng-container *ngIf="(auth.appUser$ | async) as user; else anonymousUser">
  <li> content... </li>
</ng-container>

Upvotes: 1

Related Questions