我正尝试通过以下方式在我的模板中使用可观察对象:
<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>
在我的模块中:
isAuth(): Observable<boolean> {
return this.loginservice.getAuthenticated()
.map(user => {
if (user) {
if (user.hasOwnProperty('uid')) {
return true;
} else {
return false;
}
} else {
return false;
}
})
}
所以我的问题:
如果我登录并且 observable 返回 true -> 酷我的菜单项出现
但是如果 observable 返回 false -> 我的菜单是空的 -> 怎么了?
最佳答案
您的表达式 *ngIf="!isAuth() | async"
将被解释为:
isAuth() -> returns observable
!isAuth() -> returns false because of !
!isAuth() | async -> actually trying to subscribe on false which should fail
只需使用 !(isAuth() | async)
即可。
您遇到的另一个问题是您在加载模板时两次调用服务器。这是您可能不想做的事情。
最后,这个
isAuth(): Observable<boolean> {
return this.loginservice.getAuthenticated()
.map(user => {
if (user) {
if (user.hasOwnProperty('uid')) {
return true;
} else {
return false;
}
} else {
return false;
}
})
}
可以写成
this.loginservice.getAuthenticated()
.map(user => user && user.hasOwnProperty('uid'))
并且有 Angular 5+ 作为
this.loginservice.getAuthenticated().pipe(
map(user => user && user.hasOwnProperty('uid'))
)
关于angular - 在模板中使用 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41168263/