【问题标题】:Angular 2 RouterStateSnapshot not returning correct urlAngular 2 RouterStateSnapshot 没有返回正确的 url
【发布时间】:2017-05-26 12:35:54
【问题描述】:

我正在尝试根据 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] }
];

希望有人能帮忙

【问题讨论】:

    标签: javascript angular angular2-routing


    【解决方案1】:

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

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 2019-03-21
      相关资源
      最近更新 更多