在模板中使用 Observable

Use Observable in 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>

在我的模块中:

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

所以我的问题:

如果我登录并且可观察 returns true -> 很酷我的菜单项出现

但是如果可观察 returns 为假 -> 我的菜单是空的 -> 怎么了?

您的表达式 *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'))
)