我已经搜索了互联网,但找不到答案。我发现路由守卫上的这篇文章在浏览器刷新上不起作用,并且解决方案不起作用,因为我认为它是特定于 Firebase 的。
app.module.ts
@NgModule({
declarations: [
AppComponent,
HeaderComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpModule,
MaterialModule,
HomeModule,
LoginModule,
SettingsModule,
RoutingModule
],
exports: [
RoutingModule
],
providers: [
AuthGuardService,
AuthService,
/* other services */
],
bootstrap: [AppComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }
我在各种路由模块中定义了各种路由:
app-routing.module.ts(全局路由配置)
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
// Default route
{
path: '**',
redirectTo: '',
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class RoutingModule {}
登录路由.module.ts
const routes: Routes = [
// Login
{
path: '',
component: LoginComponent
}
];
家庭路由.module.ts
const routes: Routes = [
// Home
{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuardService],
canActivateChild: [AuthGuardService]
}
];
设置-routing.module.ts
const routes: Routes = [
// Settings
{
path: 'settings',
component: SettingsComponent,
canActivate: [AuthGuardService]
}
];
下面是我使用的 Auth Guard,它是根据这篇关于使用 jwt 登录的文章修改的:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanLoad, Route } from '@angular/router';
import { AuthService } from '../services';
import { JwtHelper } from 'angular2-jwt';
@Injectable()
export class AuthGuardService implements CanActivate {
private jwtHelper: JwtHelper = new JwtHelper();
constructor(
private authService: AuthService,
private router: Router
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.navigateToLogin();
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.navigateToLogin();
}
private navigateToLogin(): boolean {
if (localStorage.getItem('token')) {
// if logged in & token not expired, return true
if(!this.jwtHelper.isTokenExpired(localStorage.getItem('token'))) {
return true;
}
// if token expired, logout
else {
this.authService.logout();
}
}
// re route to login
this.router.navigate(['']);
return false;
}
}
使用当前的实现,以下是行为:
如果用户未登录
- 去
/
上班 - 转到
/home
或/settings
在 URL 中重定向到/
(登录屏幕) - 转到任何随机 URL(如
/fjdsakfjkla
)重定向到/
(登录屏幕)
如果用户已登录
- 在 URL 中键入
/home
或/settings
指示用户正确的路线 - 转到任何随机 URL(如
/fjdsakfjkla
)重定向到/home
- 类型
/
(登录页面)将用户定向到/home
问题是,登录后,在浏览器刷新期间,您被重定向到/home
. 如果用户登录,我该如何做到这一点,浏览器刷新将保持路由?例如,如果我在/settings
,浏览器刷新不会重新路由到/home
并保持在/settings
.
当前:
/settings
→浏览器刷新→/home
期望:/settings
→浏览器刷新→/settings