在我的应用程序中,用户登录后有一个主页和其他一些页面。问题是,当我进入这些其他页面之一并刷新页面时,它再次将我送回家。这是我的 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'
}
];
应用组件有路由器 socket
<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 每次我刷新页面时都会触发守卫,所以每次它都会在家里重定向我。就是这样。谢谢
最佳答案
路由的顺序很重要,因为路由器在匹配路由时使用优先匹配的策略,所以更具体的路由应该放在不太具体的路由之上。
只有当没有其他路由首先匹配时,路由器才会选择它。
引用: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'
}
];
关于刷新另一个页面时, Angular 路由重定向到主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61477433/