*ngIf not working as expected with observable

RiesvGeffen picture RiesvGeffen · Apr 3, 2018 · Viewed 15.8k times · Source

So I have these 2 buttons:

<a class="router-link nav-item" routerLink="/login" *ngIf="!isLoggedIn$ | async">
  Login
</a>
<a class="router-link nav-item" (click)="onLogout()" *ngIf="isLoggedIn$ | async">
  Logout
</a>

And the logout button works perfectly, as soon as the user is logged in the button appears. But the login button never appears.

This is the code behind the isLoggedIn$:

isLoggedIn$: Observable<boolean>;

ngOnInit() {
  this.isLoggedIn$ = this.authService.isLoggedIn;
}

AuthService:

private loggedIn = new BehaviorSubject<boolean>(false);

get isLoggedIn() {
  return this.loggedIn.asObservable();
}

Hope this is enough information and the problem is clear, thanks in advance!

Answer

Tomasz Kula picture Tomasz Kula · Apr 3, 2018

Put the async pipe in parenthesis.

<a class="router-link nav-item" routerLink="/login" *ngIf="!(isLoggedIn$ | async)">
  Login
</a>
<a class="router-link nav-item" (click)="onLogout()" *ngIf="isLoggedIn$ | async">
  Logout
</a>