Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Observable in Template

I am trying to use an observable in my template by:

<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:

if i am loggedin and the observable returns true -> cool my menu item appears

but if the observable returns false -> my menu is empty -> whats wrong ?

like image 279
Harald Wiesinger Avatar asked Dec 15 '16 15:12

Harald Wiesinger


1 Answers

Your expression *ngIf="!isAuth() | async" is going to 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 you have is that you call the server twice while loading the template. This is something that you probably don't want to do.

And finally, this

isAuth(): Observable<boolean> {
  return 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 with angular 5+ as

this.loginservice.getAuthenticated().pipe(
  map(user => user && user.hasOwnProperty('uid'))
)
like image 184
smnbbrv Avatar answered Nov 06 '22 13:11

smnbbrv