Search code examples
angularangular-routingangular-routercanactivate

How to prefix automatically language in path of route with Angular 14


I try to add the language of customer directly in the path like

/en/dashboard

And if a customer go to the web site with an older link, like

/home

I want to add automatically the default language in the url like /en/home

This is my routes :

{
  path: ":lang",
  resolve: {
    language: isValidLanguage
  },
  children: [
    {
      path: "dashboard",
      component: Dashboard
    },
    {
      path: "home",
      component: Home
    },
    {
      path: "**",
      redirectTo: "/en/dashboard",
      pathMatch: "prefix"
    }
  ]
}

Actually my router redirect the older urls to /en/dashboard


Solution

  • My solution involves using canActivate to redirect the user to the desired route based on the language set.

    You have to define the valid languages on the can activate so that it checks for invalid routes.

      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
        const validLangs = ['en'];
        console.log(route, state);
        if (!validLangs.some((lang: string) => state.url.includes(lang))) {
          return this.router.createUrlTree(['en', ...state.url.split('/').filter(x => x)]);
        }
        return true;
      }
    }
    

    Full Code:

    import {
      Routes,
      ActivatedRouteSnapshot,
      RouterStateSnapshot,
      CanActivate,
      Router,
    } from '@angular/router';
    import { ExampleComponent } from './example/example.component';
    import { HelloComponent, EmptyComponent } from './hello.component';
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class CanActivateTeam implements CanActivate {
      constructor(private router: Router) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
        const validLangs = ['en'];
        console.log(route, state);
        if (!validLangs.some((lang: string) => state.url.includes(lang))) {
          return this.router.createUrlTree([
            'en',
            ...state.url.split('/').filter((x) => x),
          ]);
        }
        return true;
      }
    }
    
    export const routes: Routes = [
      {
        path: ':lang',
        children: [
          {
            path: 'dashboard',
            component: ExampleComponent,
          },
          {
            path: 'home',
            component: HelloComponent,
          },
          {
            path: '**',
            component: EmptyComponent,
            canActivate: [CanActivateTeam],
          },
        ],
      },
    ];
    

    Stackblitz Demo