gpt4 book ai didi

如果 URL 是手动编写的,则 Angular 刷新应用程序

转载 作者:行者123 更新时间:2023-12-03 18:21:33 26 4
gpt4 key购买 nike

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

最佳答案

您可以使用

RouterModule.forRoot(
ROUTES,
{ useHash: true }
)],

哈希将阻止应用程序重新加载。
因此,当您在地址栏上按 Enter 时,应用程序只会更改要显示的组件。

关于如果 URL 是手动编写的,则 Angular 刷新应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51168786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com