Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngIf not working as expected with observable

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!

like image 496
RiesvGeffen Avatar asked Apr 03 '18 13:04

RiesvGeffen


3 Answers

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>
like image 172
Tomasz Kula Avatar answered Nov 15 '22 06:11

Tomasz Kula


I like the answer with *ngIf and Else approach, but your version can also be optimized to prevent double subscription.

<ng-container *ngIf="{ isLoggedIn: (isLoggedIn$ | async) } as observables">
  <a class="router-link nav-item" routerLink="/login" *ngIf="!observables.isLoggedIn">
    Login
  </a>
  <a class="router-link nav-item" (click)="onLogout()" *ngIf="observables.isLoggedIn">
  Logout
  </a>
</ng-container>
like image 32
proximab Avatar answered Nov 15 '22 06:11

proximab


You can also refactor to use the else part of ngIf directive:

<a class="router-link nav-item" (click)="onLogout()" *ngIf="isLoggedIn$ | async; else loginBlock">
    Logout
</a>
<ng-template #loginBlock>
    <a class="router-link nav-item" routerLink="/login">
        Login
    </a>
</ng-template>

You can see more examples in the docs.

like image 22
Adrian Fâciu Avatar answered Nov 15 '22 08:11

Adrian Fâciu