Search code examples
angularangular-routingangular-router

how to redirect with query parameters from router file


I have a router that accepts queryParams, it can include or not a queryParam for language for example: ?lang=de

when I navigate using router it works:

this.router.navigate(['/routeToNavigate'], { queryParams: queryParams })

My problem is in routing file:

const APP_ROUTES: Routes = [
{
  path: '',
  canActivate: [ValidUserGuard],
  runGuardsAndResolvers: 'always',
  children: [
    {
      path: '',
      redirectTo: '/main',
      pathMatch: 'full'
    } 
  ]
},
  {path: '**', redirectTo: ''}
];

my problem is in this redirectTo, I lost here the queryParams if they exists.

for example urls that dont work are:

http://mypage.com?lang=de http://mypage.com/invalidRoute?lang=de

How can I include queryParms in this "redirectTo"??


Solution

  • I solved it, if someone has interest:

      {
        path: '',
        children: [],
        canActivate: [RedirectorGuard],
        pathMatch: 'full'
      },
    
    export class RedirectorGuard implements CanActivate {
    
    constructor(
      private router: Router
    ) {}
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
     const queryParams =  route.queryParams.lang ? {
       lang: route.queryParams.lang
     } : {};
    
      return this.router.navigate(['/main'],  { queryParams: queryParams })
          .then(() => true);
      }
    }