angular - 刷新另一个页面时,角度路由重定向到主页
问题描述
在我的应用程序中,用户登录后我有一个主页和其他一些页面。问题是,当我在这些其他页面之一中并刷新页面时,它再次将我发送到家。这是我的Routes
:
const routes: Routes = [
{
path: '', redirectTo: '/home', pathMatch: 'full'
},
{
path: 'login', component: LoginComponent
},{
path: 'list', component: ListComponent, canActivate : [AuthGuardService]
},{
path: 'home', component: HomeComponent, canActivate : [AuthGuardService]
},{
path: 'detail/:id', component: HomeComponent, canActivate : [AuthGuardService],
},{
path: '**', redirectTo: 'login' ,pathMatch: 'full'
}
];
应用程序组件具有路由器插座
<div [ngClass]="{'container': (isLoggedIn$ | async), 'mt-2': (isLoggedIn$ | async)}" class="h-100">
<router-outlet></router-outlet>
</div>
那么,我期待什么?首先,如果我是“列表”页面(localhost:4200/list
)并且我刷新了这个页面,它应该留在那里。在那一页。但现在它把我重定向到localhost:4200/home
. 当然,当我单击一个列表项时,它应该将我发送到,localhost:4200/detail/itemId
但它总是将我发送到家。谢谢
使用 AuthGuardService 进行编辑:
export class AuthGuardService implements CanActivate {
constructor(private route : Router, private store: Store<AppState>) {}
canActivate() {
return this.store
.pipe(
select(isLoggedIn),
tap(loggedIn => {
if (!loggedIn) {
this.route.navigate(['login']);
}
})
)
}
}
我添加登录效果
login$ = createEffect(() =>
this.actions$
.pipe(
ofType(userActions.login),
tap(action => {
localStorage.setItem('userInfo',
JSON.stringify(action.user))
this.router.navigate(['home']);
})
)
,{dispatch: false});
解决方案:
好吧,经过几个小时的调试,我找到了解决方案。基本上我删除了 this.router.navigate(['home']); 在 AuthGuardService 中,一旦用户登录,我就把它放在组件的登录功能上。把 this.router.navigate(['home']); 在 AuthGuardService 中,每次我刷新页面时都会触发警卫,因此每次它都会在家里重定向我。而已。谢谢
解决方案
路由的顺序很重要,因为路由器在匹配路由时使用先匹配获胜策略,因此更具体的路由应该放在不太具体的路由之上。
- 首先列出具有静态路径的路由
- 后跟一个空路径路由,它与默认路由匹配。
- 通配符路由位于最后,因为它匹配每个 URL。
只有在没有其他路由首先匹配时,路由器才会选择它。
参考:https ://angular.io/guide/router#route-order
所以你改变顺序如下
const routes: Routes = [
{
path: 'login', component: LoginComponent
},{
path: 'list', component: ListComponent, canActivate : [AuthGuardService]
},{
path: 'home', component: HomeComponent, canActivate : [AuthGuardService]
},{
path: 'detail/:id', component: HomeComponent, canActivate : [AuthGuardService],
}
{
path: '', redirectTo: '/home', pathMatch: 'full'
},
,{
path: '**', redirectTo: 'login' ,pathMatch: 'full'
}
];
推荐阅读
- email - (中间值).sendEmail(...).promise 不是函数
- flutter - 如何在 Wrap Widget 中换行
- javascript - 如何使用 React Router Dom 在 ReactJS 上正确路由页面
- c# - 使用带有 .AddClientAccessTokenHandler() 扩展名的 HttpClient 时,不包括角色声明
- configuration - Ansible Inventory 多行库存数组?
- c++ - 通过套接字传输数据[TCP] 如何在 c/c++ 中打包多个整数并使用 send() recv() 传输数据?
- android - 如何在 Kotlin 中添加图像微调器
- python - Pandas:用特定值替换一行中的所有单词,列表中的单词除外
- python - WSGI 应用程序无法从 html 表单接收 post 方法
- java - 是否可以配置 spring-openapi 以在 v3 api-docs 中生成可预测的订单输出?