【发布时间】:2018-12-12 14:33:36
【问题描述】:
我正在使用 Angular 6,但在更改路线时遇到了问题。 如果我使用 routerLink 或 navigate() 方法浏览应用程序,它可以正常工作,因为它只加载新模块(如果需要)。 但例如,如果我在这个链接中:localhost:8080/home,我点击 URL,取消 'home',写 'profile' 并按 Enter,它会正确进入配置文件页面,但重新加载应用程序(也是应用程序组件)。为什么?我想不通。 这是我的路线:
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
也许问题出在 auth-guard 上?
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private store: Store<fromApp.AppState>, private route: ActivatedRoute, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.store.select('auth')
.pipe(take(1),
map((authState: fromAuth.State) => {
if (authState.authenticated) {
return true;
} else {
let sessionStorageToken: string = sessionStorage.getItem('token');
if (sessionStorageToken) {
this.store.dispatch(new AuthActions.Login());
this.store.dispatch(new AuthActions.SetToken(sessionStorageToken));
return true;
} else {
let url = state.url;
this.router.navigate(['/login', { redirectTo: url }]);
return false;
}
}
}));
}
}
这是 profile.module.ts:
@NgModule({
declarations: [
ProfileComponent
],
imports: [
CommonModule,
FormsModule
]
})
export class ProfileModule { }
【问题讨论】:
-
您必须按两次回车键。我不知道为什么,我从来没有研究过。之后有目的吗?你想达到什么目标?
-
这是我在 Angular 中的第一个项目,通常我使用 AngularJS..在 AngularJS 中,例如,如果我在家,然后我去配置文件,然后我回家(也通过 url 手动)页面和应用程序未重新加载!问题是我使用 Redux 来管理状态和登录用户,所以如果我转到“个人资料”页面并且重新加载了应用程序,我会丢失关于登录用户的状态部分
-
对于任何投反对票的人:我很高兴这个问题从未发生在您身上。
标签: angular angular-routing angular-router canactivate