B
B
Bowen2016-10-21 22:56:05
Angular
Bowen, 2016-10-21 22:56:05

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+"})

I couldn't find anything similar. Perhaps I overlooked something, or maybe angular2 does not know how to do this yet.
I would be grateful for help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bowen, 2016-12-26
@Bowen

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
  ]
})

Now, in the files where I had routes, I added to the desired route:
It looks like this
export const routes: Routes = [{
    path: 'post/:id',
    loadChildren: './post?chunkName=post',
    canActivate: ['RouterParamsGuard']
}];

It could probably be implemented in another way, but I still did not understand how it could be done.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question