Angular 2 router v3 observable defender with ngrx

I am trying to create an "auth application" with redux (ngrx), and I am trying to use the state of my application in a secret defender. Here you can see my github: https://github.com/tamasfoldi/ngrx-auth/tree/router Here is what my guard looks like:

@Injectable()
export class SecretGuard implements CanActivate {
  constructor(private store: Store<AppState>, private router: Router) {
  }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.store.let(getLoginState())
      .map(state$ => state$.isLoggedIn)
  }
}

It returns with the isLoggedIn attribute, which should be OK, because the router allows promises and observables, but the router blocks it when I go to the secret part. Here are my routes:

export const appRoutes: Routes = [
  {
    path: '',
    redirectTo: 'auth',
    pathMatch: 'full'
  },
  {
    path: 'auth',
    children: [
      { path: '', redirectTo: 'login', pathMatch: 'full' },
      { path: 'login', component: LoginComponent },
      { path: 'register', component: RegisterComponent }
    ]
  },
  {
    path: 'secret',
    canActivate: [SecretGuard],
    children: [
      { path: '', redirectTo: 'default', pathMatch: 'full' },
      { path: 'default', component: DefaultSecretComponent }
    ]
  }
];

In redux, I get the init state, so I also tried to skip the first emission in my observable, but it does not work. Here is the pass code:

@Injectable()
export class SecretGuard implements CanActivate {
  constructor(private store: Store<AppState>, private router: Router) {
  }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.store.let(getLoginState())
      .skip(1)
      .map(state$ => state$.isLoggedIn)
  }
}

auth- AuthService, , "". , ngrx? ?

+4
1

, " " (:

https://github.com/ngrx/store#getstate-getvalue-and-value

import 'rxjs/add/operator/take';

function getState(store: Store<State>): State {
    let state: State;
    store.take(1).subscribe(s => state = s);
    return state;
}

@Injectable()
export class SecretGuard implements CanActivate {
  constructor(private store: Store<AppState>, private router: Router) { }

  canActivate():boolean {
    return getState(this.store).login.isLoggedIn;
  }
}
+4

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


All Articles