Bretteux
Bretteux

Reputation: 11

Angular 4 - Router redirectTo using variable segment

In the routing Routes below, I'm receiving the following error when im trying to fetch http://localhost:4200/

ERROR Error: Uncaught (in promise): Error: Cannot redirect to '/:userCountry/:userLanguage/home'. Cannot find ':userCountry'. Error: Cannot redirect to '/:userCountry/:userLanguage/home'. Cannot find ':userCountry'. at ApplyRedirects.webpackJsonp.../../../router/@angular/router.es5.js.ApplyRedirects.findPosParam (router.es5.js:1784)

Every other routing path is working, it's only the redirectTo who seems to not substitute the value of variable userCountry (and userLanguage also).

Any help would be much appreciated.

const appRoutes: Routes = [
   { path: '', redirectTo: '/:userCountry/:userLanguage/home', pathMatch: 'full' },
   { path: ':userCountry/:userLanguage/home', component: HomeComponent },
   { path: ':userCountry/:userLanguage/about', loadChildren: './about/about.module#AboutModule' },
   { path: ':userCountry/:userLanguage/terms', loadChildren: './terms/terms.module#TermsModule' },
   { path: ':userCountry/:userLanguage/privacy', loadChildren: './privacy/privacy.module#PrivacyModule' },
   { path: '**', component: PageNotFoundComponent }
];

My variables already have value when the error appends.

Here is an extract from my console.log()

[AppRoutingModule.constructor]this.userLanguage=fr
    [AppRoutingModule.constructor]this.userCountry=ca  
    ...  
    ERROR Error: Uncaught (in promise): Error: Cannot redirect to '/:userCountry/:userLanguage/home'. Cannot find ':userCountry'

Upvotes: 0

Views: 1584

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

You need to pass default values to userCountry and userLanguage for route matching when it is in the '' route. You can do like

const appRoutes: Routes = [
   { path: '', redirectTo: '/germany/ge/home', pathMatch: 'full' },
   { path: ':userCountry/:userLanguage/home', component: HomeComponent }
   ...
}

Upvotes: 1

Related Questions