带有 ngrx 的 Angular 2 router v3 observable guard

标签 angular angular2-routing ngrx angular2-router3

我正在尝试使用 redux(ngrx) 创建一个“auth 应用程序”,并且我正在尝试在 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)
  }
}

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

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 的 auth 功能,它工作正常,但该解决方案不是“redux-like”。你能帮我解决如何让它与 ngrx 一起工作吗?或者我不能在守卫中使用我的 appstate?

最佳答案

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

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

关于带有 ngrx 的 Angular 2 router v3 observable guard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39849060/

相关文章:

javascript - PrimeNG 数据表日期范围过滤器

angular - Angular 2 模块之间的路由

javascript - 无需订阅即可获取 ngrx 选择器的当前值

javascript - 设计一个规模化的 ngrx 商店

valueChanges 上的 Angular 7 FormControl 获得旧值

javascript - 如何从 Angular 6 中的组件中提取文本进行翻译 (ngx-translate)

angular - 尝试将 Stomp over SockJS 添加到 Angular 应用程序 : TS2307 Cannot find module

Angular 2 : 404 error occur when I refresh through the browser

angular - 无法获取 CanActivate 守卫中惰性模块的路由参数

angular - 如何在ngrx Angular2中将数据从父路由传递到子路由