【发布时间】:2018-05-09 06:58:07
【问题描述】:
我的Anuglar 4 应用程序有多个路由,在下面的示例中只有两个路由 - 日志记录和项目列表。所以基本上有两条路线:http://localhost:4200/#/ 和http://localhost:4200/#/items。当我在http://localhost:4200/#/items 并重新加载页面时,它会自动将我导航到http://localhost:4200/#/,在我看来这是错误的行为。有什么好的方法可以预防吗?目前我在http://localhost:4200/#/items 并重新加载页面以保持在同一页面时?
下面我发布一种可能对您有所帮助的配置:
<base href="/">
imports: [
RouterModule.forRoot([
{path: '', component: LoginComponent},
{path: 'items', component: ItemListComponent, canActivate: [AuthGuard]},
])
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptor, multi: true},
{provide: LocationStrategy, useClass: HashLocationStrategy},
AuthenticationService,
AuthGuard,
],
AuthGuard:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthenticationService) {
}
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isLoggedIn;
}
}
@Injectable()
export class AuthenticationService extends DataService{
private _isLoggedIn: boolean;
constructor(http: HttpClient) {
super(http);
this._isLoggedIn = false;
this.url = '/api/auth';
}
get isLoggedIn(): boolean{
return this._isLoggedIn;
}
set isLoggedIn(value: boolean){
this._isLoggedIn = value;
}
然后服务器返回令牌。供您重新加载后的信息,在 localStorage 中仍然保留有效的令牌
【问题讨论】:
-
这与服务器配置有关,您可能需要设置服务器来处理刷新,以便它返回主页 i:e index.html 并且路由会占用它从那里
-
从 items 路由中取出 AuthGuard 再试试看问题是否依然存在?
-
@ChauTran 我删除了 AuthGuard 并且它有效。是否有任何解决方法可以与 AuthGuard 一起使用?
-
这与您的应用程序没有从您尝试获取令牌以实现 AuthGuard 的任何位置获取令牌有关。我可以看看你的 AuthGuard 文件吗?
-
查看更新。
标签: javascript angular routing reload