Answer the question
In order to leave comments, you need to log in
Does Angular 2 allow route parameter validation at the routing level?
Good evening.
Here is an example of how to implement this in Symfony:
@Route("/blog/{page}", name="blog_list", requirements={"page": "\d+"})
Answer the question
In order to leave comments, you need to log in
Decided this way:
import { Injectable } from '@angular/core';
import { CanActivate , ActivatedRouteSnapshot } from '@angular/router';
import { map, every } from 'lodash';
/**
* Список параметров
* Сам список можете вынести в отдельном файле(я же для теста указал тут)
* @type {Object}
*/
const gp = {
action: 'add|edit',
id: '[0-9]'
};
@Injectable()
export class RouterGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot) {
let access: Array<boolean> = [];
map(route.params, (v: any, k: any) => access.push(new RegExp(gp[k], 'g').test(v)));
return every(access, Boolean);
}
};
import RouterParamsGuard from './router-params.guard';
@NgModule({
imports: [
BrowserModule,
HttpModule,
AppRoutingModule
],
declarations: [
AppComponent,
HomeComponent,
NotFoundComponent
],
providers: [{
provide: APP_BASE_HREF,
useValue: '/'
}, {
provide: LocationStrategy,
useClass: PathLocationStrategy
},
{
provide: 'RouterParamsGuard',
useClass: RouterParamsGuard
},
AppStore
],
bootstrap: [
AppComponent
]
})
export const routes: Routes = [{
path: 'post/:id',
loadChildren: './post?chunkName=post',
canActivate: ['RouterParamsGuard']
}];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question