W3cubDocs

/Angular 7

Router

class

An NgModule that provides navigation and URL manipulation capabilities.

class Router {
  constructor(rootComponentType: Type<any>, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[])
  events: Observable<Event>
  routerState: RouterState
  errorHandler: ErrorHandler
  malformedUriErrorHandler: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
  navigated: boolean
  urlHandlingStrategy: UrlHandlingStrategy
  routeReuseStrategy: RouteReuseStrategy
  onSameUrlNavigation: 'reload' | 'ignore'
  paramsInheritanceStrategy: 'emptyOnly' | 'always'
  urlUpdateStrategy: 'deferred' | 'eager'
  relativeLinkResolution: 'legacy' | 'corrected'
  config: Routes
  url: string
  initialNavigation(): void
  setUpLocationChangeListener(): void
  getCurrentNavigation(): Navigation | null
  resetConfig(config: Route[]): void
  ngOnDestroy(): void
  dispose(): void
  createUrlTree(commands: any[], navigationExtras: NavigationExtras = {}): UrlTree
  navigateByUrl(url: string | UrlTree, extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>
  navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>
  serializeUrl(url: UrlTree): string
  parseUrl(url: string): UrlTree
  isActive(url: string | UrlTree, exact: boolean): boolean
}

See also

Constructor

Creates the router service.

constructor(rootComponentType: Type<any>, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[])

Parameters
rootComponentType Type
urlSerializer UrlSerializer
rootContexts ChildrenOutletContexts
location Location
injector Injector
loader NgModuleFactoryLoader
compiler Compiler
config Route[]

Properties

Property Description
events: Observable<Event> Read-only.

An event stream for routing events in this NgModule.

routerState: RouterState Read-only.

The current state of routing in this NgModule.

errorHandler: ErrorHandler

A handler for navigation errors in this NgModule.

malformedUriErrorHandler: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree

Malformed uri error handler is invoked when Router.parseUrl(url) throws an error due to containing an invalid character. The most common case would be a % sign that's not encoded and is not part of a percent encoded sequence.

navigated: boolean

True if at least one navigation event has occurred, false otherwise.

urlHandlingStrategy: UrlHandlingStrategy

Extracts and merges URLs. Used for AngularJS to Angular migrations.

routeReuseStrategy: RouteReuseStrategy

The strategy for re-using routes.

onSameUrlNavigation: 'reload' | 'ignore'

How to handle a navigation request to the current URL. One of:

  • 'ignore' : The router ignores the request.
  • 'reload' : The router reloads the URL. Use to implement a "refresh" feature.
paramsInheritanceStrategy: 'emptyOnly' | 'always'

How to merge parameters, data, and resolved data from parent to child routes. One of:

  • 'emptyOnly' : Inherit parent parameters, data, and resolved data for path-less or component-less routes.
  • 'always' : Inherit parent parameters, data, and resolved data for all child routes.
urlUpdateStrategy: 'deferred' | 'eager'

Defines when the router updates the browser URL. The default behavior is to update after successful navigation. However, some applications may prefer a mode where the URL gets updated at the beginning of navigation. The most common use case would be updating the URL early so if navigation fails, you can show an error message with the URL that failed. Available options are:

  • 'deferred', the default, updates the browser URL after navigation has finished.
  • 'eager', updates browser URL at the beginning of navigation.
relativeLinkResolution: 'legacy' | 'corrected'

See RouterModule for more information.

config: Routes Declared in constructor.
url: string Read-only.

The current URL.

Methods

Sets up the location change listener and performs the initial navigation.

initialNavigation(): void

Parameters

There are no parameters.

Returns

void

Sets up the location change listener.

setUpLocationChangeListener(): void

Parameters

There are no parameters.

Returns

void

The current Navigation object if one exists

getCurrentNavigation(): Navigation | null

Parameters

There are no parameters.

Returns

Navigation | null

Resets the configuration used for navigation and generating links.

resetConfig(config: Route[]): void

Parameters
config Route[]

The route array for the new configuration.

Returns

void

Usage Notes

router.resetConfig([
 { path: 'team/:id', component: TeamCmp, children: [
   { path: 'simple', component: SimpleCmp },
   { path: 'user/:name', component: UserCmp }
 ]}
]);

ngOnDestroy(): void

Parameters

There are no parameters.

Returns

void

Disposes of the router.

dispose(): void

Parameters

There are no parameters.

Returns

void

Applies an array of commands to the current URL tree and creates a new URL tree.

createUrlTree(commands: any[], navigationExtras: NavigationExtras = {}): UrlTree

Parameters
commands any[]

An array of commands to apply.

navigationExtras NavigationExtras

Optional. Default is {}.

Returns

UrlTree: The new URL tree.

When given an activate route, applies the given commands starting from the route. When not given a route, applies the given command starting from the root.

Usage Notes

// create /team/33/user/11
router.createUrlTree(['/team', 33, 'user', 11]);

// create /team/33;expand=true/user/11
router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);

// you can collapse static segments like this (this works only with the first passed-in value):
router.createUrlTree(['/team/33/user', userId]);

// If the first segment can contain slashes, and you do not want the router to split it, you
// can do the following:

router.createUrlTree([{segmentPath: '/one/two'}]);

// create /team/33/(user/11//right:chat)
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);

// remove the right secondary node
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);

// assuming the current url is `/team/33/user/11` and the route points to `user/11`

// navigate to /team/33/user/11/details
router.createUrlTree(['details'], {relativeTo: route});

// navigate to /team/33/user/22
router.createUrlTree(['../22'], {relativeTo: route});

// navigate to /team/44/user/22
router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});

Navigate based on the provided URL, which must be absolute.

navigateByUrl(url: string | UrlTree, extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>

Parameters
url string | UrlTree

An absolute URL. The function does not apply any delta to the current URL.

extras NavigationExtras

An object containing properties that modify the navigation strategy. The function ignores any properties in the NavigationExtras that would change the provided URL.

Optional. Default is { skipLocationChange: false }.

Returns

Promise<boolean>: A Promise that resolves to 'true' when navigation succeeds, to 'false' when navigation fails, or is rejected on error.

Example
router.navigateByUrl("/team/33/user/11");

// Navigate without updating the URL
router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });

Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute.

navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>

Parameters
commands any[]
extras NavigationExtras

Optional. Default is { skipLocationChange: false }.

Returns

Promise<boolean>

Returns a promise that:

  • resolves to 'true' when navigation succeeds,
  • resolves to 'false' when navigation fails,
  • is rejected when an error happens.
Example
router.navigate(['team', 33, 'user', 11], {relativeTo: route});

// Navigate without updating the URL
router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});

The first parameter of navigate() is a delta to be applied to the current URL or the one provided in the relativeTo property of the second parameter (the NavigationExtras).

In order to affect this browser's history.state entry, the state parameter can be passed. This must be an object because the router will add the navigationId property to this object before creating the new history item.

Serializes a UrlTree into a string

serializeUrl(url: UrlTree): string

Parameters
url UrlTree
Returns

string

Parses a string into a UrlTree

parseUrl(url: string): UrlTree

Parameters
url string
Returns

UrlTree

Returns whether the url is activated

isActive(url: string | UrlTree, exact: boolean): boolean

Parameters
url string | UrlTree
exact boolean
Returns

boolean

© 2010–2019 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v7.angular.io/api/router/Router