rvdm
rvdm

Reputation: 213

angular router param match regex

I would like to start all of my url's with a language which match an array of strings or a Regex

const languages = ['nl', 'en', 'de', 'fr'] or const languageRegex = /(nl|en|de|fr)/g

my routeConfig is as follows

const appRoutes: Routes = [
    {
        path: '',
        pathMatch: 'full',
        redirectTo: 'en/configuration',
    },
    {
        children: [
            { path: '', pathMatch: 'full', redirectTo: 'configuration' },
            {
                loadChildren:
                    '../modules/booking-flow/configuration.module#ConfigurationModule',
                path: RouteHelper.paths.configuration,
            },
            {
                loadChildren:
                    '../modules/booking-flow/personal-info.module#PersonalInfoModule',
                path: RouteHelper.paths.personalInfo,
            },
            {
                loadChildren:
                    '../modules/booking-flow/summary.module#SummaryModule',
                path: RouteHelper.paths.summary,
            },
            {
                loadChildren:
                    '../modules/booking-flow/payment-method.module#PaymentMethodModule',
                path: RouteHelper.paths.paymentMethod,
            },
            {
                loadChildren:
                    '../modules/booking-flow/confirmation.module#ConfirmationModule',
                path: RouteHelper.paths.confirmation,
            },
            {
                component: ErrorPageComponent,
                path: RouteHelper.paths.errorNotFound,
            },
            {
                path: '**',
                pathMatch: 'full',
                redirectTo: RouteHelper.paths.errorNotFound,
            },
        ],
        component: null,
        path: ':language',
        runGuardsAndResolvers: 'always',
    },
];

It is a pity this doesn't work, it's a pretty readable config in my opinion:

path: ':language(/nl|en|de|fr/g)',

I would like to get the following pattern.

Upvotes: 0

Views: 3913

Answers (2)

Amir Arbabian
Amir Arbabian

Reputation: 3699

So as i see, you won't achieve that with just router configuration, it doesn't have such capabilities. Instead you can use RouteGuard to check whether language parameter is in ['nl', 'en', 'de', 'fr'], and if it doesn't you can just return an UrlTree (in case of angular 7.1+) of not found page or redirect user manually with router (angular <= 7.1).

The guard can look like this:

const allowedLanguages = ['nl', 'en', 'de', 'fr'];

@Injectable({
  providedIn: 'root'
})
export class LanguageGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.next.params.pipe(
        map(params => {
            return params && allowedLanguages.includes(params.language)
               ? true
               : this.router.parseUrl(RouteHelper.paths.errorNotFound)
        })
    );
  }
}

Afterwards you just need to apply this guard to your parent route. Hope that helps.

Upvotes: 2

ambs
ambs

Reputation: 487

I think there are better ways to solve your problem; if indeed your problem is related to supporting different languages in your application.

ngx-translate is a supported, well known/documented library that allows you to internationalise your application, without much hassle.

The library allows you to provide the languages that your application supports, where you'll supply JSON files containing the correct language translations you require, per language you support.

They'll look like this:

{
    "title": "My title"
}

The library provides pipes, directives, which can be used in HTML like this:

<span translate>title</span>

<span> {{ 'title' | translate }}</span>

Both would render My Title - within a span element.

The library allows you to do much more, such as parameter interpolation - where you can pass dynamic values to your translations. It also provides services for you to make translations within your code.

Upvotes: 0

Related Questions