Search code examples
angularangular-router

Angular routing redirects to parent route instead of child on page refresh


I have the following app routing:

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children:
      [
        {
          path: '',
          redirectTo: '/dashboard',
          pathMatch: 'full'
        },
        {
          path: 'dashboard',
          component: DashboardComponent,
          children:
            [
              {path: 'profile', component: ProfileComponent},
              {path: 'user-management', component: UserManagementComponent},
              {path: 'role-management', component: RoleManagementComponent}
            ]
        }
      ]
  },
  {path: 'login', component: LoginComponent},
  {path:'token-verify',component:TwoFactorVerificationComponent}
];

So here is my problem. Let's say I am on route dashboard. Navigating to /profile or /user-management works fine using the angular router. However I am facing the following problem: if I am on route /dashboard/user-management or /dashboard/role-management and do a page refresh I will get redirected to /dashboard/profile. Any ideas what I am doing wrong?

Here is my auth quard

import { Injectable } from "@angular/core";
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from "@angular/router";
import { Observable } from "rxjs";
import { UserService } from "../services/user.service";
import { TokenService } from "../services/token.service";

@Injectable({
  providedIn: "root"
})
export class AuthGuard implements CanActivate {
  constructor(
    private tokenService: TokenService,
    private userService: UserService
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    console.log(`Requested -> state: ${state.url}`);
    if (this.tokenService.isLoggedIn()) {
      console.log("isLogged in and will return true");
      return true;
    } else {
      console.log("will fail and go to login");
      this.userService.redirectToLogginPage();
      return false;
    }
  }
}

Whenever I do refresh the page the auth guard gets called and it prints

Requested -> state: /dashboard/user-management 
auth.guard.ts:26 isLogged in and will return true

in case I am logged in

After some digging I found that If I refresh the page on dashboard/user-management the OnInit method of that component is actually called but I get redirected in /dashboard/profile


Solution

  • So I finally found what was wrong.In the dashboard component (the parent one) this was happening on ngOnInit()

    ngOnInit() {
        // @TODO
        // refactor using async await
        this.userService
          .getProfile()
          .then((res: any) => {
            console.log(res);
            const user: UserIdentity = res;
            this.user_email = user.emailId;
            if (this.userService.checkrole(user.roles, "ADMIN")) {
              //this.router.navigate(['/dashboard']);
            }
          })
          .catch(error => {
            console.error(error);
          });
      }
    

    I removed this line and it worked.The reasonn is that after the child view was rendered the parent view would say "Hey child view go back to the parent view"