带有 ngrx 的 Angular 2 路由器 v3 可观察防护

buc*_*aci 5 angular2-routing ngrx angular2-router3 angular

我正在尝试使用 redux(ngrx) 创建一个“身份验证应用程序”,并且我正在尝试在秘密守卫中使用我的应用程序状态。在这里你可以看到我的 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)
  }
}
Run Code Online (Sandbox Code Playgroud)

它返回 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 }
    ]
  }
];
Run Code Online (Sandbox Code Playgroud)

在 redux 中,我收到了 init 状态,因此我也尝试跳过可观察对象中的第一次发射,但它都不起作用。这是跳过代码:

@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)
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用我的 AuthService 的 auth 功能,它可以正常工作,但该解决方案不是“类似 redux”的。你能帮我解决如何让它与 ngrx 一起工作吗?或者我不能在警卫中使用我的应用程序状态?

Sas*_*sxa 4

您可以同步从商店获取价值,不需要“传输所有内容”(:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我没有这个问题,因为我很早就决定有两个减速器 - `auth` 和 `user`。我仅将“auth”用于 true/false/pending,将“user”用于用户配置文件数据,然后在防护中使用“auth”,在组件中使用“user”进行重定向。在登录/注销期间需要做更多的工作 - 我正在调度 `LoginUserAction` 和 `LoginAuthAction` 但以后更容易处理。我希望它对于延迟加载也很有用,我可以将“auth”打包在**AppModule**中,并将“user”打包在**AdminModule**中... (2认同)