wiktus239
wiktus239

Reputation: 1420

How to restrict Angular2 routing parameters?

Given this simple routing example I'd like to be able to restrict the :page argument.

const appRoutes: Routes = [
  { path: ':page', component: PageFoundComponent },
  { path: '**', component: PageNotFoundComponent }
];

Preferably with an Array of Strings. Expected behaviour here is to check the :page to be one of the Array elements and route to the PageNotFoundComponent if it is not there.

// pseudo code
let knownPages = ["welcome", "shop", "about"];
(...)
{ path: ':page@knownPages', component: PageFoundComponent }

The concept is borrowed from Symfony2 routing mechanism.

How should I approach it?

Upvotes: 2

Views: 1977

Answers (2)

jmckenney
jmckenney

Reputation: 41

You will want to use Router Guards. In specific, likely the CanActivate Guard.

import { AuthGuard }                from '../auth-guard.service';

const adminRoutes: Routes = [
  {
    path: ':page',
    component: Component,
    canActivate: [AuthGuard]
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(adminRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class RoutingModule {}

Note that you can use multiple guards. One could return true if the path is in an array, one could be related to authentication, one could be related to roles, etc.

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657821

You can use a custom UrlMatcher that was introduced recently

{ path: ':page', component: PageFoundComponent, matcher: ... },

but I haven't found any docs about it yet.

See also https://angular.io/docs/ts/latest/api/router/index/Routes-type-alias.html

Upvotes: 4

Related Questions