Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular routing optional parameter validation

I have routing in my application where first parameter is not dedicated. It depends on which languages my application have

const routes: Routes = [
  {
    path: ':lang',
    component: MainComponent,
    children: [
      {
        path: '',
        loadChildren: './modules/home/home.module#HomeModule',
      },
          {
        path: 'offers',
        loadChildren: './modules/offers/offers.module#OffersModule',
      },
      {
        path: 'blog',
        loadChildren: './modules/blog/blog.module#BlogModule',
      },
    ]
 }
]

Can I do validation here where if user will enter incorrect url it will redirect to 404 page?

For example domain.com/en/blog is valid url but domain.com/anotherurl not.

I'm using version 7 of angular

like image 877
gsiradze Avatar asked Jul 12 '19 11:07

gsiradze


Video Answer


1 Answers

Yes, this is possible. What you can do is use a resolver:

const routes: Routes = [
  {
    path: ':lang',
    component: MainComponent,
    resolve: {foo: LanguageResolverService}
    children: []

The resolver would look something like this:

@Injectable()
export class LanguageResolverService implements Resolve<null> {
    constructor(private router: Router) {}

    public resolve(route: ActivatedRouteSnapshot, router) {

        const language = route.paramMap.get('lang');

        if(allowedLanguages.includes(language)) {
            return null;
        } else {
            this.router.navigate(['404']);
        }           
    }
}

Now, if your language exists, the resolver will simply continue to the desired route. If it does not, you can redirect the user to any page you'd like.

like image 160
skolldev Avatar answered Sep 29 '22 21:09

skolldev