简体   繁体   English

带有Firebase实时数据库的Angular2 + Auth Guard

[英]Angular2+ auth guard with firebase realtime database

I am trying to set a guard to angular routes depending on user's data on firebase realtime database. 我正在尝试根据Firebase实时数据库上的用户数据为角度路由设置防护措施。 I've set admin's privilege as dashboard: true on user's realtime database section ( like this picture ). 我已将管理员的特权设置为仪表板:在用户的实时数据库部分( 如此图片 )为true。 And I'd like to give a permission to enter some specific routes only if the user has dashboard: true property on his/her database. 而且,我只想允许用户输入某些特定的路线,前提是该用户在他/她的数据库中具有仪表板:true属性。 I tried below code. 我尝试下面的代码。 But it always redirects to the root route (localhost:4200) 但是它总是重定向到根路由(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;
      }
    });
}
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);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM