2016-10-04 72 views
4

我试图创建一个“auth应用程序”与REDX(ngrx),我试图在秘密警卫中使用我的应用程序状态。在这里,你可以看到我的github:https://github.com/tamasfoldi/ngrx-auth/tree/router 这是我的后卫看起来像:Angular 2路由器v3可观察的守卫与ngrx

@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属性,它应该是可以的,因为路由器解决的承诺和可观的,但路由器块,当我浏览到秘密部分。这里是我的路线:

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

在终极版,我收到了初始状态,所以我也试图跳过我观察到的第一个发射,但它没有工作。 这里是跳过代码:

@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的身份验证功能,但这种解决方案不是“终极版样”。你可以帮助我如何使它与ngrx工作?或者我无法在守卫中使用我的appstate?

回答

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

由于它是工作,但如果我添加一些错误处理逻辑,它(我认为这是因为初始状态的isLoggedIn属性为false,如果我跳过(1),重新加载就可以了,但是在试图从导航栏,因为它跳过每一个。你有一些想法如何解决这个? – bucicimaci

+0

它工作,如果我使用debounceTime但不知道如果是最好的解决方案 – bucicimaci

+2

我没有这个问题,因为我很早就决定有两个reducer - 'auth'和'user'。我使用'auth'来验证用户配置文件数据的真/假/待处理和'user',然后在守卫中使用'auth',在组件中使用'user'来重定向。在登录/注销期间它有点更多工作 - 我正在调度'LoginUserAction'和'LoginAuthAction',但稍后更容易处理。我期望它也可以用于延迟加载,我可以在** AppModule **和** AdminModule **中包装'auth' ...' – Sasxa