在我的应用程序中,用户登录后有一个主页和其他一些页面。问题是,当我进入其他页面之一并且刷新页面时,它再次将我送回家。这是我的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});
您可以尝试使用onSameUrlNavigation重新加载到应用模块中吗?
@NgModule({
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
exports: [RouterModule]
})
路由的顺序很重要,因为路由器在匹配路由时会使用首个匹配获胜策略,因此,应将更具体的路由置于不那么具体的路由之上。
仅当没有其他路由首先匹配时,路由器才会选择它。
参考: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'
}
];