interface
deprecated
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.
Deprecated: Class-based Route
guards are deprecated in favor of functional guards. An injectable class can be used as a functional guard using the inject
function: canMatch: [() => inject(myGuard).canMatch()]
.
interface CanMatch { canMatch(route: Route, segments: UrlSegment[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree }
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.
canMatch() | ||||||
---|---|---|---|---|---|---|
|
route | Route | |
segments | UrlSegment[] |
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/router/CanMatch