On this page
CanMatch
interface
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.
interface CanMatch {
canMatch(route: Route, segments: UrlSegment[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
}
Description
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, id: string, 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.
You can alternatively provide an in-line function with the CanMatchFn
signature:
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamComponent,
loadChildren: () => import('./team').then(mod => mod.TeamModule),
canMatch: [(route: Route, segments: UrlSegment[]) => true]
},
{
path: '**',
component: NotFoundComponent
}
])
],
})
class AppModule {}
Methods
canMatch()
|
||||||
---|---|---|---|---|---|---|
|
route |
Route |
|
segments |
UrlSegment[] |
Returns
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v14.angular.io/api/router/CanMatch