我正在使用 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 { }