Angular 2 RouterStateSnapshot没有返回正确的URL [英] Angular 2 RouterStateSnapshot not returning correct url
问题描述
我正在尝试根据angular的文档在登录后获取重定向. https://angular.io/docs/ts/latest/guide/router.html#!#teach-authguard-to-authenticate
I'm trying to get the redirect after login working based on the documentation from angular. https://angular.io/docs/ts/latest/guide/router.html#!#teach-authguard-to-authenticate
我的设置基本相同,尽管某些文件名不同.
I got basically the same setup albeit that some filenames are different.
问题是,当我在authGuard中记录RouterStateSnapshot网址时, 它总是从app-routing.module.ts('/countries')输出第一个路由,而不是例如/countries/france/34
The problem is that when i log the RouterStateSnapshot url in the authGuard, it wil always output the first route from app-routing.module.ts ('/countries') instead of e.g. /countries/france/34
authGuard
authGuard
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url = state.url;
console.log(state); // always outputs first route from app-routing.module.ts ('/countries')
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.userService.isLoggedIn()) {
return true;
}
this.userService.redirectUrl = url;
console.log(this.userService.redirectUrl);
// not logged in so redirect to login page
this.router.navigate(['/login']);
return false;
}
应用程序路由模块
const routes: Routes = [
{ path: '', redirectTo: 'countries', pathMatch: 'full', canActivate: [AuthGuard]},
{ path: 'login', loadChildren: './authentication/authentication.module#AuthenticationModule' },
{ path: 'countries', loadChildren: './countries/countries.module#CountriesModule'},
...
];
国家路由模块
const routes: Routes = [
{ path: '', component: CountriesComponent, canActivate: [AuthGuard] },
{ path: ':name/:id', component: CountryComponent, canActivate: [AuthGuard] }
];
希望有人可以提供帮助
推荐答案
您对所有路径使用相同的AuthGuard
,因此您看到的结果是,您可以为不同的路由创建不同的Auth Guard,也可以使用某些逻辑识别何时调用相同的canActivate
.
you are using same AuthGuard
for all the paths, hence you are seeing that result, you can either create different Auth guards for different routes or have some logic to identify when the same canActivate
is called.
希望这会有所帮助!
这篇关于Angular 2 RouterStateSnapshot没有返回正确的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!