我正试图用redux(ngrx)创建一个"auth应用程序“,并试图在秘密守卫中使用我的应用程序状态。在这里,您可以看到我的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属性应该是OK的,因为路由器解析了承诺并可以观察到,但是当我导航到秘密部分时,路由器会阻塞它。以下是我的路线:
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状态,所以我也尝试跳过我可观察到的第一次发射,但是它都不起作用。下面是跳过的代码:
@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样”。你能帮我把它和ngrx一起用吗?还是我不能用我的名字当警卫?
发布于 2016-10-04 15:33:35
您可以从商店中同步获取值,不需要“流所有东西”(:
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;
}
}https://stackoverflow.com/questions/39849060
复制相似问题