Use observable in template

I am trying to use observable in my template:

<md-nav-list> <a md-list-item *ngIf="!isAuth() | async" [routerLink]="['login']" (click)="sidenav.toggle()">Login</a> <a md-list-item *ngIf="isAuth() | async" (click)="logout()" (click)="sidenav.toggle()">Logout</a> </md-nav-list> 

and in my module:

  isAuth(): Observable<boolean> { return this.loginservice.getAuthenticated() .map(user => { if(user){ if(user.hasOwnProperty('uid')){ return true; } else { return false; } } else { return false; } }) } 

So my problem is:

if I am registered and observable returns true → will cool my menu item.

but if the observable returns false → my menu is empty → what is wrong?

+6
source share
1 answer

Your expression *ngIf="!isAuth() | async" will be interpreted as:

 isAuth() -> returns observable !isAuth() -> returns false because of ! !isAuth() | async -> actually trying to subscribe on false which should fail 

Just use !(isAuth() | async) instead.

Another problem is that you call the server twice when loading the template. This is something you probably don't want to do.

And finally this

 this.loginservice.getAuthenticated() .map(user => { if(user){ if(user.hasOwnProperty('uid')){ return true; } else { return false; } } else { return false; } }) 

can be written as

 this.loginservice.getAuthenticated() .map(user => user && user.hasOwnProperty('uid')) 

and angular 5+ as

 this.loginservice.getAuthenticated().pipe( map(user => user && user.hasOwnProperty('uid')) ) 
+10
source

Source: https://habr.com/ru/post/1013197/


All Articles