Angular2 + auth后卫与firebase实时数据库

时间:2018-06-10 08:33:17

标签: angular firebase firebase-realtime-database firebase-authentication

我正在尝试根据firebase实时数据库中的用户数据设置防范角度路由。我将admin的权限设置为仪表板:在用户的实时数据库部分(like this picture)上为true。只有当用户在他/她的数据库上有dashboard:true属性时,我才允许输入一些特定的路由。我试过下面的代码。但它总是重定向到根路由(localhost:4200)

    canActivate(): Observable<boolean> {

    return this.firebaseAuth.authState.map(auth => {
      if (auth) {
        this.authService.getUserData(auth.uid).subscribe(userData => {
          if (userData['dashboard'] === true) {
            return true;
          } else {
            this.router.navigate(['/login']);
            return false;
          }
        })
      } else {
        this.router.navigate(['/login']);
        return false;
      }
    });
}

1 个答案:

答案 0 :(得分:0)

canActivate(): Observable<boolean> {

    return this.firebaseAuth.authState.switchMap(auth => {
        if (auth)
            return this.authService.getUserData(auth.uid).map(userData => {
                if (userData['dashboard'] === true)
                    return true;

                this.router.navigate(['/login']);
                return false;
            });

        this.router.navigate(['/login']);
        return of(false);
    });
}