CanMatch
Interface that a class can implement to be a guard deciding if a Route
can be matched.
If all guards return true
, navigation continues and the Router
will use the Route
during
activation. If any guard returns false
, the Route
is skipped for matching and other Route
configurations are processed instead.
canMatch
MaybeAsync<GuardResult>
Description
Interface that a class can implement to be a guard deciding if a Route
can be matched.
If all guards return true
, navigation continues and the Router
will use the Route
during
activation. If any guard returns false
, the Route
is skipped for matching and other Route
configurations are processed instead.
The following example implements a CanMatch
function that decides whether the
current user has permission to access the users page.
class UserToken {}class Permissions { canAccess(user: UserToken, route: Route, segments: UrlSegment[]): boolean { return true; }}@Injectable()class CanMatchTeamSection implements CanMatch { constructor(private permissions: Permissions, private currentUser: UserToken) {} canMatch(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean { return this.permissions.canAccess(this.currentUser, route, segments); }}
Here, the defined guard function is provided as part of the Route
object
in the router configuration:
@NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, loadChildren: () => import('./team').then(mod => mod.TeamModule), canMatch: [CanMatchTeamSection] }, { path: '**', component: NotFoundComponent } ]) ], providers: [CanMatchTeamSection, UserToken, Permissions]})class AppModule {}
If the CanMatchTeamSection
were to return false
, the router would continue navigating to the
team/:id
URL, but would load the NotFoundComponent
because the Route
for 'team/:id'
could not be used for a URL match but the catch-all **
Route
did instead.