Angular 2 router v3 observable guard with ngrx

Angular 2 router v3 observable guard with ngrx

我正在尝试使用 redux(ngrx) 创建一个 "auth app",并且我正在尝试在 secret guard 中使用我的应用程序状态。在这里你可以看到我的github:https://github.com/tamasfoldi/ngrx-auth/tree/router 这是我的守卫的样子:

@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)
  }
}

它 returns 带有 isLoggedIn 属性,这应该没问题,因为路由器解析了 promises 和 observable,但是当我导航到秘密部分时路由器阻止了它。这是我的路线:

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 }
    ]
  }
];

在 redux 中,我收到了 init 状态,所以我也尝试跳过我的 observable 中的第一次发射,但它都不起作用。 这是跳过代码:

@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)
  }
}

如果我使用我的 AuthService 的授权功能,它工作正常,但该解决方案不是 "redux-like"。你能帮我解决如何让它与 ngrx 一起工作吗?或者我无法在守卫中使用我的 appstate?

您可以从商店同步获取价值,不需要 "stream everything" (:

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;
  }
}