Angular 2 RouterStateSnapshot没有返回正确的URL

时间:2017-05-26 12:35:55

标签: javascript angular angular2-routing

我尝试根据angular的文档在登录后进行重定向。 https://angular.io/docs/ts/latest/guide/router.html#!#teach-authguard-to-authenticate

我得到了基本相同的设置,尽管有些文件名不同。

问题是当我在authGuard中记录RouterStateSnapshot url时, 它总是会从app-routing.module.ts(' / countries')输出第一条路线而不是例如/国家/法国/ 34

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

希望有人可以提供帮助

1 个答案:

答案 0 :(得分:1)

您对所有路径使用相同的AuthGuard,因此您看到了结果,您可以为不同的路由创建不同的Auth保护,或者有一些逻辑来识别何时调用相同的canActivate

希望这会有所帮助!!