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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With