Search code examples
angularlazy-loadingangular-router

Angular redirect to parameter in lazy loaded module


I have some lazy loaded routes as following:

const routes: Routes = [
    {
        path: ':lang',
        loadChildren: './components/home/home.module#HomeModule',
        // redirectTo: "en"
    },
    {
        path: ':id/customers',
        loadChildren: './components/customers/customers.module#CustomersModule'
    },
    {
        path: 'products',
        loadChildren: './components/products/products.module#ProductsModule'
    }
];

When I open the page with this url: http://localhost:4200/en it works fine. But the user doesn't know to add en parameter to the url, so the page doesn't load without parameter. So, I must redirect it to /en. But when I use redirectTo: "en" I get the following errors:

Error: Invalid configuration of route ':lang': redirectTo and loadChildren cannot be used together

I found something about this error, but doesn't relate to my case. Any idea?


Solution

  • Setting redirectTo on the route :lang means: if the user is on that route, it should be redirected to /en. That's not what you want. You want to redirect the user to /enwhen the path is the root path. So you need to add an empty path route and redirect from there:

    {
        path: '',
        redirectTo: '/en',
        pathMatch: 'full'
    }