qwe*_*567 4 angular2-routing angular
我有以下问题。我制作了一个CanActivate Guard,可以在其中登录到“债务”组件。我的问题是,当我登录后,我想将用户重定向到债务组件(因为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);
}
})
})
}
Run Code Online (Sandbox Code Playgroud)
任何我的应用程序路由
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]}
];
Run Code Online (Sandbox Code Playgroud)
我所做的虽然有点骇人听闻,但却可以完美地工作:
首先,我确实Guard
在LoginCompoment
路线上设置了一个。
{ path: 'login', component: LoginComponent, canActivate: [AuthGuard] }
Run Code Online (Sandbox Code Playgroud)
然后,我使用RouterStateSnapshot
来获取我的URL状态的单个实例,指示我用户想要访问的内容。
然后,我可以在Guard中管理案件:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
有关快照的文档链接:https : //angular.io/docs/ts/latest/guide/router.html#!# sts = Snapshot:% 20the% 20no-observable% 20alternative
为了使它适合您的情况,您只需要setLoggedInState()
使它适应似乎已经存在的情况即可。
注意:我将此解决方案称为HACK,因为您实际上在设置防护措施的Login
同时,即使用户未经过身份验证,防护措施仍将允许用户访问它。仍然运作良好。
归档时间: |
|
查看次数: |
4065 次 |
最近记录: |