我有跟踪问题。我已经做了一个CanActivate警卫,如果你登录,你可以“去”债务组件。我的问题是,当我登录,我想重定向用户到债务组件(因为RegistrationComponent是默认的),但它不工作(实际上我的页面阻塞。我什么也做不了)。我的CanActivate函数
export class AuthGuardService implements CanActivate {
constructor(private router: Router) { }
canActivate(): Promise<boolean>{
return checkIfAuth().then(() => {
setLoggedIn(true);
this.router.navigate(['/debts']); // <- broken :(
return true;
}).catch(() => {
setLoggedIn(false);
this.router.navigate(['/login']); // <- broken :(
return false;
})
}
}
export function checkIfAuth () {
return new Promise((resolve, reject) => {
firebase.auth().onAuthStateChanged((user) => {
if(user){
return resolve(true);
}
else{
return reject(false);
}
})
})
}任何我的app.routing
const APP_ROUTES: Routes = [
{ path: '', redirectTo: '/registration', pathMatch: 'full' },
{ path: 'registration', component: RegistrationComponent },
{ path: 'login', component: LoginComponent },
{ path: 'myaccount', component: AccountComponent, canActivate: [AuthGuardService]},
{ path: 'debts', component: DebtsComponent, canActivate: [AuthGuardService]}
];发布于 2017-01-12 10:07:34
我所做的是一次黑客攻击,但效果完美无缺:
首先,我在我的Guard路由上设置了一个LoginCompoment。
{ path: 'login', component: LoginComponent, canActivate: [AuthGuard] }然后,我使用RouterStateSnapshot获取状态的单个实例,指示用户试图达到的目标。
然后,我可以管理警卫的案件:
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
...
/**
* Protects the routes to reach with authentication
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// Set user authentication state depending on the token's existance
this.authService.setLoggedInState();
// Check user authentication state
if (this.authService.isAuthenticated) {
// Explicit navigation to '/login' while the user is already authenticated
if (state.url === '/login') {
this.router.navigate(['/dashboard']); // Debts for you
}
return true;
} else {
// Allow route to './login' to get authenticated
if (state.url === '/login') {
return true;
}
// Explicit navigation to any URL while not being authenticated
this.router.navigate(['/login']);
return false;
}
}要使它在您的情况下工作,您只需调整setLoggedInState()以适应您的情况,这似乎您已经有了。
N.B :,我把这个解决方案称为HACK,因为您实际上设置了一个Login的守卫,而它仍然允许用户访问它,即使他没有经过身份验证。还是很管用的。
https://stackoverflow.com/questions/41608830
复制相似问题