我试图创建一个" auth app"与redux(ngrx)和我试图在秘密警卫中使用我的app状态。在这里你可以看到我的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,但是当我导航到秘密部分时路由器会阻止它。这是我的路线:
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中,我收到初始状态,所以我也尝试跳过我的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功能它正常工作,但该解决方案不是&#34; redux-like&#34;。你能帮我解决一下如何让它与ngrx一起工作吗?或者我无法在警卫中使用我的appstate?
答案 0 :(得分: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;
}
}