Angular 2 RouterStateSnapshot not returning correct url

心不动则不痛 提交于 2019-12-12 05:15:00

问题


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.

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

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

App routing module

const routes: Routes = [
    { path: '', redirectTo: 'countries', pathMatch: 'full', canActivate: [AuthGuard]},
    { path: 'login', loadChildren: './authentication/authentication.module#AuthenticationModule' },
    { path: 'countries', loadChildren: './countries/countries.module#CountriesModule'},
    ...
];

Country routing module

const routes: Routes = [
    { path: '', component: CountriesComponent, canActivate: [AuthGuard] },
    { path: ':name/:id', component: CountryComponent, canActivate: [AuthGuard] }
];

Hope someone can help


回答1:


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.

Hope this helps!!



来源:https://stackoverflow.com/questions/44201794/angular-2-routerstatesnapshot-not-returning-correct-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!