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 ?
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'))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With