在模板中使用Observable

问题描述 投票:8回答:1

我试图在我的模板中使用一个observable:

<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 - >我的菜单是空的 - >什么是错的?

angular typescript angularfire2
1个回答
13
投票

你的表达式*ngIf="!isAuth() | async"将被解释为:

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

只需使用!(isAuth() | async)

您遇到的另一个问题是在加载模板时调用服务器两次。这是你可能不想做的事情。

最后,这个

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'))

并且角度为5+

this.loginservice.getAuthenticated().pipe(
  map(user => user && user.hasOwnProperty('uid'))
)
© www.soinside.com 2019 - 2024. All rights reserved.