Within my application, there is a homepage that appears after the user logs in, along with some other pages. However, I've encountered an issue where when I navigate to one of these other pages and then refresh the page, it redirects me back to the homepage. Here are my 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'
}
];
The app-component contains the router outlet
<div [ngClass]="{'container': (isLoggedIn$ | async), 'mt-2': (isLoggedIn$ | async)}" class="h-100">
<router-outlet></router-outlet>
</div>
What I expect is for when I am on the "list" page (localhost:4200/list
) and I refresh the page, it should remain on that page. Instead, it currently redirects me to localhost:4200/home
.
Additionally, clicking on a list item should take me to localhost:4200/detail/itemId
, but it always sends me back to the home page. Thank you
Edit made with 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']);
}
})
)
}
}
I have introduced the login effect
login$ = createEffect(() =>
this.actions$
.pipe(
ofType(userActions.login),
tap(action => {
localStorage.setItem('userInfo',
JSON.stringify(action.user))
this.router.navigate(['home']);
})
)
,{dispatch: false});
SOLUTION:
After spending several hours debugging, I finally discovered the solution. Essentially, I removed this.router.navigate(['home']); from the AuthGuardService and instead placed it in the login function of the component as soon as the user logs in. By placing this.router.navigate(['home']); in the AuthGuardService, the guard was triggered every time I refreshed the page, leading to constant redirection to the home page. That's all. Thank you