pan*_*s72 7 angular-routing canactivate angular angular-router
我正在使用 Angular 6,但我在更改路线时遇到了问题。如果我使用 routerLink 或 navigate() 方法浏览应用程序,它会正常工作,因为它只加载新模块(如有必要)。但是,例如,如果我在此链接中:localhost:8080/home,我单击 URL,取消“主页”,输入“配置文件”并按 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 { }
Run Code Online (Sandbox Code Playgroud)
也许问题出在 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;
}
}
}));
}
}
Run Code Online (Sandbox Code Playgroud)
这是 profile.module.ts:
@NgModule({
declarations: [
ProfileComponent
],
imports: [
CommonModule,
FormsModule
]
})
export class ProfileModule { }
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以使用
RouterModule.forRoot(
ROUTES,
{ useHash: true }
)],
Run Code Online (Sandbox Code Playgroud)
哈希值将阻止应用程序重新加载。因此,当您在地址栏上按 Enter 键时,应用程序将仅更改要显示的组件。
当您routerLink在 Angular 内部导航时,底层 JavaScript 正在确定向浏览器提供什么。这意味着当 URL 地址通过 Angular 路由器更改时,它会获取更改并相应地为组件提供服务。
当您手动更新 URL 并按 Enter 时,就像进入一个新网页一样。这意味着服务器将需要重新服务基础网站,http://localhost:1234然后应用程序将在那里处理路由,/profile并提供所需的组件。
我试图以一种非常简单的方式解释它,要获得更详尽的解释,请查看Angular 文档
| 归档时间: |
|
| 查看次数: |
5844 次 |
| 最近记录: |