Angular2 CanActivate Defender not working

I use return Observable<boolean>for canActivate(). For testing, the following function was configured, and it is correctly enabled, the component is displayed.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  return Observable.from([{ admin: true }]).map(x =>
  {
    if (x.admin) return true;
    return false;
  });
}

However, the behavior of the actual code is that I remain on the login component, despite the console output indicating that the route should be activated. The only real difference from the above test is that I call the service this.auth.isAdmin()instead of using Observable.from. The result this.auth.isAdmin()is Observable<boolean>true.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  const isAdmin$ = this.auth.isAdmin();
  return isAdmin$.map(x =>
  {
    console.log('isAdmin returned ' + x);
    if (!x) {
      console.log('redirectToLogin');
      this.auth.redirectToLogin(state.url);
      return false;
    } else {
      console.log('canActivate = true');
      return true;
    }
  });  
}

Here is the route:

{
  path: 'admin',
  canActivate: [AdminGuard],
  children: [
    ...adminRoutes
  ]
},

Here is my console output:

isAdmin returned false
admin-guard.service.ts:27redirectToLogin
auth.service.ts:36 navigating to stored path "/admin"
auth.service.ts:21 Object {isAdmin: true, isPaid: false, $key: "xYFs8kMDpKdYKxDw4AL21FtnSWn1"}
admin-guard.service.ts:25 isAdmin returned true
admin-guard.service.ts:31 canActivate = true

And here is isAdmin () function in case this is interesting:

isAdmin(): Observable<boolean> {
    if (!this.auth) return Observable.from([false]);
    const uid = this.auth.uid;
    return this.af.database.object(`user/${uid}`).do(x => console.log(x)).map(x => x.isAdmin);
}
+4
source share
1

, isAdmin, . AngularFire2 FirebaseObjectObservable ; .

, , . , first ( take(1)), :

canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable<boolean> {
  const isAdmin$ = this.auth.isAdmin();
  return isAdmin$.first().map(x =>
  {
    console.log('isAdmin returned ' + x);
    if (!x) {
      console.log('redirectToLogin');
      this.auth.redirectToLogin(state.url);
      return false;
    } else {
      console.log('canActivate = true');
      return true;
    }
  });  
}

, . , Angular first , .

+7

Source: https://habr.com/ru/post/1654298/


All Articles