docs: update router api documentation (#37980)

Edit descriptions, usage examples, and add links to be complete and consistent with API reference doc style

PR Close #37980
This commit is contained in:
Judy Bogart 2020-06-01 14:58:07 -07:00 committed by Andrew Kushnir
parent 019a696a6a
commit 6c9401c338
6 changed files with 220 additions and 128 deletions

View File

@ -148,7 +148,6 @@ export declare class GuardsCheckStart extends RouterEvent {
toString(): string; toString(): string;
} }
/** @deprecated */
export declare type InitialNavigation = true | false | 'enabled' | 'disabled' | 'legacy_enabled' | 'legacy_disabled'; export declare type InitialNavigation = true | false | 'enabled' | 'disabled' | 'legacy_enabled' | 'legacy_disabled';
export declare type LoadChildren = LoadChildrenCallback | DeprecatedLoadChildren; export declare type LoadChildren = LoadChildrenCallback | DeprecatedLoadChildren;

View File

@ -22,6 +22,7 @@ import {UrlSegment, UrlSegmentGroup} from './url_tree';
* *
* @see `Route` * @see `Route`
* @see `Router` * @see `Router`
* @see [Router configuration guide](guide/router#configuration)
* @publicApi * @publicApi
*/ */
export type Routes = Route[]; export type Routes = Route[];
@ -45,14 +46,12 @@ export type UrlMatchResult = {
* for `Route.matcher` when a combination of `path` and `pathMatch` * for `Route.matcher` when a combination of `path` and `pathMatch`
* is not expressive enough. Cannot be used together with `path` and `pathMatch`. * is not expressive enough. Cannot be used together with `path` and `pathMatch`.
* *
* @param segments An array of URL segments. * The function takes the following arguments and returns a `UrlMatchResult` object.
* @param group A segment group. * * *segments* : An array of URL segments.
* @param route The route to match against. * * *group* : A segment group.
* @returns The match-result. * * *route* : The route to match against.
* *
* @usageNotes * The following example implementation matches HTML files.
*
* The following matcher matches HTML files.
* *
* ``` * ```
* export function htmlFiles(url: UrlSegment[]) { * export function htmlFiles(url: UrlSegment[]) {
@ -94,8 +93,10 @@ export type ResolveData = {
/** /**
* *
* A function that is called to resolve a collection of lazy-loaded routes. * A function that is called to resolve a collection of lazy-loaded routes.
* Must be an arrow function of the following form:
* `() => import('...').then(mod => mod.MODULE)`
* *
* Often this function will be implemented using an ES dynamic `import()` expression. For example: * For example:
* *
* ``` * ```
* [{ * [{
@ -104,10 +105,7 @@ export type ResolveData = {
* }]; * }];
* ``` * ```
* *
* This function _must_ match the form above: an arrow function of the form * @see [Route.loadChildren](api/router/Route#loadChildren)
* `() => import('...').then(mod => mod.MODULE)`.
*
* @see `Route#loadChildren`.
* @publicApi * @publicApi
*/ */
export type LoadChildrenCallback = () => Type<any>|NgModuleFactory<any>|Observable<Type<any>>| export type LoadChildrenCallback = () => Type<any>|NgModuleFactory<any>|Observable<Type<any>>|
@ -115,13 +113,12 @@ export type LoadChildrenCallback = () => Type<any>|NgModuleFactory<any>|Observab
/** /**
* *
* A string of the form `path/to/file#exportName` that acts as a URL for a set of routes to load, * A function that returns a set of routes to load.
* or a function that returns such a set.
* *
* The string form of `LoadChildren` is deprecated (see `DeprecatedLoadChildren`). The function * The string form of `LoadChildren` is deprecated (see `DeprecatedLoadChildren`). The function
* form (`LoadChildrenCallback`) should be used instead. * form (`LoadChildrenCallback`) should be used instead.
* *
* @see `Route#loadChildren`. * @see `loadChildrenCallback`
* @publicApi * @publicApi
*/ */
export type LoadChildren = LoadChildrenCallback|DeprecatedLoadChildren; export type LoadChildren = LoadChildrenCallback|DeprecatedLoadChildren;
@ -129,10 +126,11 @@ export type LoadChildren = LoadChildrenCallback|DeprecatedLoadChildren;
/** /**
* A string of the form `path/to/file#exportName` that acts as a URL for a set of routes to load. * A string of the form `path/to/file#exportName` that acts as a URL for a set of routes to load.
* *
* @see `Route#loadChildren` * @see `loadChildrenCallback`
* @publicApi * @publicApi
* @deprecated the `string` form of `loadChildren` is deprecated in favor of the proposed ES dynamic * @deprecated The `string` form of `loadChildren` is deprecated in favor of the
* `import()` expression, which offers a more natural and standards-based mechanism to dynamically * `LoadChildrenCallback` function which uses the ES dynamic `import()` expression.
* This offers a more natural and standards-based mechanism to dynamically
* load an ES module at runtime. * load an ES module at runtime.
*/ */
export type DeprecatedLoadChildren = string; export type DeprecatedLoadChildren = string;
@ -154,7 +152,7 @@ export type QueryParamsHandling = 'merge'|'preserve'|'';
* *
* A policy for when to run guards and resolvers on a route. * A policy for when to run guards and resolvers on a route.
* *
* @see `Route#runGuardsAndResolvers` * @see [Route.runGuardsAndResolvers](api/router/Route#runGuardsAndResolvers)
* @publicApi * @publicApi
*/ */
export type RunGuardsAndResolvers = export type RunGuardsAndResolvers =
@ -371,7 +369,8 @@ export type RunGuardsAndResolvers =
* *
* Lazy loading speeds up application load time by splitting the application * Lazy loading speeds up application load time by splitting the application
* into multiple bundles and loading them on demand. * into multiple bundles and loading them on demand.
* To use lazy loading, provide the `loadChildren` property instead of the `children` property. * To use lazy loading, provide the `loadChildren` property in the `Route` object,
* instead of the `children` property.
* *
* Given the following example route, the router will lazy load * Given the following example route, the router will lazy load
* the associated module on demand using the browser native import system. * the associated module on demand using the browser native import system.
@ -470,7 +469,7 @@ export interface Route {
*/ */
children?: Routes; children?: Routes;
/** /**
* A `LoadChildren` object specifying lazy-loaded child routes. * An object specifying lazy-loaded child routes.
*/ */
loadChildren?: LoadChildren; loadChildren?: LoadChildren;
/** /**

View File

@ -24,7 +24,7 @@ export type NavigationTrigger = 'imperative'|'popstate'|'hashchange';
* Base for events the router goes through, as opposed to events tied to a specific * Base for events the router goes through, as opposed to events tied to a specific
* route. Fired one time for any given navigation. * route. Fired one time for any given navigation.
* *
* @usageNotes * The following code shows how a class subscribes to router events.
* *
* ```ts * ```ts
* class MyService { * class MyService {
@ -39,6 +39,7 @@ export type NavigationTrigger = 'imperative'|'popstate'|'hashchange';
* ``` * ```
* *
* @see `Event` * @see `Event`
* @see [Router events summary](guide/router#router-events)
* @publicApi * @publicApi
*/ */
export class RouterEvent { export class RouterEvent {
@ -59,6 +60,9 @@ export class NavigationStart extends RouterEvent {
* Identifies the call or event that triggered the navigation. * Identifies the call or event that triggered the navigation.
* An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`. * An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`.
* *
* @see `NavigationEnd`
* @see `NavigationCancel`
* @see `NavigationError`
*/ */
navigationTrigger?: 'imperative'|'popstate'|'hashchange'; navigationTrigger?: 'imperative'|'popstate'|'hashchange';
@ -104,6 +108,10 @@ export class NavigationStart extends RouterEvent {
/** /**
* An event triggered when a navigation ends successfully. * An event triggered when a navigation ends successfully.
* *
* @see `NavigationStart`
* @see `NavigationCancel`
* @see `NavigationError`
*
* @publicApi * @publicApi
*/ */
export class NavigationEnd extends RouterEvent { export class NavigationEnd extends RouterEvent {
@ -126,10 +134,13 @@ export class NavigationEnd extends RouterEvent {
/** /**
* An event triggered when a navigation is canceled, directly or indirectly. * An event triggered when a navigation is canceled, directly or indirectly.
* * This can happen when a route guard
* This can happen when a [route guard](guide/router-tutorial-toh#milestone-5-route-guards)
* returns `false` or initiates a redirect by returning a `UrlTree`. * returns `false` or initiates a redirect by returning a `UrlTree`.
* *
* @see `NavigationStart`
* @see `NavigationEnd`
* @see `NavigationError`
*
* @publicApi * @publicApi
*/ */
export class NavigationCancel extends RouterEvent { export class NavigationCancel extends RouterEvent {
@ -152,6 +163,10 @@ export class NavigationCancel extends RouterEvent {
/** /**
* An event triggered when a navigation fails due to an unexpected error. * An event triggered when a navigation fails due to an unexpected error.
* *
* @see `NavigationStart`
* @see `NavigationEnd`
* @see `NavigationCancel`
*
* @publicApi * @publicApi
*/ */
export class NavigationError extends RouterEvent { export class NavigationError extends RouterEvent {
@ -172,7 +187,7 @@ export class NavigationError extends RouterEvent {
} }
/** /**
*An event triggered when routes are recognized. * An event triggered when routes are recognized.
* *
* @publicApi * @publicApi
*/ */
@ -199,6 +214,8 @@ export class RoutesRecognized extends RouterEvent {
/** /**
* An event triggered at the start of the Guard phase of routing. * An event triggered at the start of the Guard phase of routing.
* *
* @see `GuardsCheckEnd`
*
* @publicApi * @publicApi
*/ */
export class GuardsCheckStart extends RouterEvent { export class GuardsCheckStart extends RouterEvent {
@ -223,6 +240,8 @@ export class GuardsCheckStart extends RouterEvent {
/** /**
* An event triggered at the end of the Guard phase of routing. * An event triggered at the end of the Guard phase of routing.
* *
* @see `GuardsCheckStart`
*
* @publicApi * @publicApi
*/ */
export class GuardsCheckEnd extends RouterEvent { export class GuardsCheckEnd extends RouterEvent {
@ -252,6 +271,8 @@ export class GuardsCheckEnd extends RouterEvent {
* Runs in the "resolve" phase whether or not there is anything to resolve. * Runs in the "resolve" phase whether or not there is anything to resolve.
* In future, may change to only run when there are things to be resolved. * In future, may change to only run when there are things to be resolved.
* *
* @see `ResolveEnd`
*
* @publicApi * @publicApi
*/ */
export class ResolveStart extends RouterEvent { export class ResolveStart extends RouterEvent {
@ -301,6 +322,8 @@ export class ResolveEnd extends RouterEvent {
/** /**
* An event triggered before lazy loading a route configuration. * An event triggered before lazy loading a route configuration.
* *
* @see `RouteConfigLoadEnd`
*
* @publicApi * @publicApi
*/ */
export class RouteConfigLoadStart { export class RouteConfigLoadStart {
@ -315,6 +338,8 @@ export class RouteConfigLoadStart {
/** /**
* An event triggered when a route has been lazy loaded. * An event triggered when a route has been lazy loaded.
* *
* @see `RouteConfigLoadStart`
*
* @publicApi * @publicApi
*/ */
export class RouteConfigLoadEnd { export class RouteConfigLoadEnd {
@ -348,7 +373,7 @@ export class ChildActivationStart {
* An event triggered at the end of the child-activation part * An event triggered at the end of the child-activation part
* of the Resolve phase of routing. * of the Resolve phase of routing.
* @see `ChildActivationStart` * @see `ChildActivationStart`
* @see `ResolveStart` * * @see `ResolveStart`
* @publicApi * @publicApi
*/ */
export class ChildActivationEnd { export class ChildActivationEnd {
@ -364,7 +389,7 @@ export class ChildActivationEnd {
/** /**
* An event triggered at the start of the activation part * An event triggered at the start of the activation part
* of the Resolve phase of routing. * of the Resolve phase of routing.
* @see ActivationEnd` * @see `ActivationEnd`
* @see `ResolveStart` * @see `ResolveStart`
* *
* @publicApi * @publicApi
@ -422,24 +447,33 @@ export class Scroll {
/** /**
* Router events that allow you to track the lifecycle of the router. * Router events that allow you to track the lifecycle of the router.
* *
* The sequence of router events is as follows: * The events occur in the following sequence:
* *
* - `NavigationStart`, * * [NavigationStart](api/router/NavigationStart): Navigation starts.
* - `RouteConfigLoadStart`, * * [RouteConfigLoadStart](api/router/RouteConfigLoadStart): Before
* - `RouteConfigLoadEnd`, * the router [lazy loads](/guide/router#lazy-loading) a route configuration.
* - `RoutesRecognized`, * * [RouteConfigLoadEnd](api/router/RouteConfigLoadEnd): After a route has been lazy loaded.
* - `GuardsCheckStart`, * * [RoutesRecognized](api/router/RoutesRecognized): When the router parses the URL
* - `ChildActivationStart`, * and the routes are recognized.
* - `ActivationStart`, * * [GuardsCheckStart](api/router/GuardsCheckStart): When the router begins the *guards*
* - `GuardsCheckEnd`, * phase of routing.
* - `ResolveStart`, * * [ChildActivationStart](api/router/ChildActivationStart): When the router
* - `ResolveEnd`, * begins activating a route's children.
* - `ActivationEnd` * * [ActivationStart](api/router/ActivationStart): When the router begins activating a route.
* - `ChildActivationEnd` * * [GuardsCheckEnd](api/router/GuardsCheckEnd): When the router finishes the *guards*
* - `NavigationEnd`, * phase of routing successfully.
* - `NavigationCancel`, * * [ResolveStart](api/router/ResolveStart): When the router begins the *resolve*
* - `NavigationError` * phase of routing.
* - `Scroll` * * [ResolveEnd](api/router/ResolveEnd): When the router finishes the *resolve*
* phase of routing successfuly.
* * [ChildActivationEnd](api/router/ChildActivationEnd): When the router finishes
* activating a route's children.
* * [ActivationEnd](api/router/ActivationStart): When the router finishes activating a route.
* * [NavigationEnd](api/router/NavigationEnd): When navigation ends successfully.
* * [NavigationCancel](api/router/NavigationCancel): When navigation is canceled.
* * [NavigationError](api/router/NavigationError): When navigation fails
* due to an unexpected error.
* * [Scroll](api/router/Scroll): When the user scrolls.
* *
* @publicApi * @publicApi
*/ */

View File

@ -36,7 +36,14 @@ import {isUrlTree} from './utils/type_guards';
/** /**
* @description * @description
* *
* Options that modify the navigation strategy. * Options that modify the `Router` navigation strategy.
* Supply an object containing any of these properties to a `Router` navigation function to
* control how the target URL should be constructed or interpreted.
*
* @see [Router.navigate() method](api/router/Router#navigate)
* @see [Router.navigateByUrl() method](api/router/Router#navigatebyurl)
* @see [Router.createUrlTree() method](api/router/Router#createurltree)
* @see [Routing and Navigation guide](guide/router)
* *
* @publicApi * @publicApi
*/ */
@ -108,13 +115,24 @@ export interface NavigationExtras {
/** /**
* How to handle query parameters in the router link for the next navigation. * How to handle query parameters in the router link for the next navigation.
* One of: * One of:
* * `merge` : Merge new with current parameters.
* * `preserve` : Preserve current parameters. * * `preserve` : Preserve current parameters.
* * `merge` : Merge new with current parameters.
* *
* The "preserve" option discards any new query params:
* ``` * ```
* // from /results?page=1 to /view?page=1&page=2 * // from /view1?page=1 to/view2?page=1
* this.router.navigate(['/view'], { queryParams: { page: 2 }, queryParamsHandling: "merge" }); * this.router.navigate(['/view2'], { queryParams: { page: 2 }, queryParamsHandling: "preserve"
* });
* ``` * ```
* The "merge" option appends new query params to the params from the current URL:
* ```
* // from /view1?page=1 to/view2?page=1&otherKey=2
* this.router.navigate(['/view2'], { queryParams: { otherKey: 2 }, queryParamsHandling: "merge"
* });
* ```
* In case of a key collision between current parameters and those in the `queryParams` object,
* the new value is used.
*
*/ */
queryParamsHandling?: QueryParamsHandling|null; queryParamsHandling?: QueryParamsHandling|null;
/** /**
@ -147,7 +165,8 @@ export interface NavigationExtras {
/** /**
* Developer-defined state that can be passed to any navigation. * Developer-defined state that can be passed to any navigation.
* Access this value through the `Navigation.extras` object * Access this value through the `Navigation.extras` object
* returned from `router.getCurrentNavigation()` while a navigation is executing. * returned from the [Router.getCurrentNavigation()
* method](api/router/Router#getcurrentnavigation) while a navigation is executing.
* *
* After a navigation completes, the router writes an object containing this * After a navigation completes, the router writes an object containing this
* value together with a `navigationId` to `history.state`. * value together with a `navigationId` to `history.state`.
@ -156,6 +175,7 @@ export interface NavigationExtras {
* *
* Note that `history.state` does not pass an object equality test because * Note that `history.state` does not pass an object equality test because
* the router adds the `navigationId` on each navigation. * the router adds the `navigationId` on each navigation.
*
*/ */
state?: {[k: string]: any}; state?: {[k: string]: any};
} }
@ -163,8 +183,8 @@ export interface NavigationExtras {
/** /**
* Error handler that is invoked when a navigation error occurs. * Error handler that is invoked when a navigation error occurs.
* *
* If the handler returns a value, the navigation promise is resolved with this value. * If the handler returns a value, the navigation Promise is resolved with this value.
* If the handler throws an exception, the navigation promise is rejected with * If the handler throws an exception, the navigation Promise is rejected with
* the exception. * the exception.
* *
* @publicApi * @publicApi
@ -185,14 +205,32 @@ export type RestoredState = {
}; };
/** /**
* Information about a navigation operation. Retrieve the most recent * Information about a navigation operation.
* navigation object with the `router.getCurrentNavigation()` method. * Retrieve the most recent navigation object with the
* [Router.getCurrentNavigation() method](api/router/Router#getcurrentnavigation) .
*
* * *id* : The unique identifier of the current navigation.
* * *initialUrl* : The target URL passed into the `Router#navigateByUrl()` call before navigation.
* This is the value before the router has parsed or applied redirects to it.
* * *extractedUrl* : The initial target URL after being parsed with `UrlSerializer.extract()`.
* * *finalUrl* : The extracted URL after redirects have been applied.
* This URL may not be available immediately, therefore this property can be `undefined`.
* It is guaranteed to be set after the `RoutesRecognized` event fires.
* * *trigger* : Identifies how this navigation was triggered.
* -- 'imperative'--Triggered by `router.navigateByUrl` or `router.navigate`.
* -- 'popstate'--Triggered by a popstate event.
* -- 'hashchange'--Triggered by a hashchange event.
* * *extras* : A `NavigationExtras` options object that controlled the strategy used for this
* navigation.
* * *previousNavigation* : The previously successful `Navigation` object. Only one previous
* navigation is available, therefore this previous `Navigation` object has a `null` value for its
* own `previousNavigation`.
* *
* @publicApi * @publicApi
*/ */
export type Navigation = { export type Navigation = {
/** /**
* The ID of the current navigation. * The unique identifier of the current navigation.
*/ */
id: number; id: number;
/** /**
@ -289,7 +327,7 @@ type LocationChangeInfo = {
/** /**
* @description * @description
* *
* A service that provides navigation and URL manipulation capabilities. * A service that provides navigation among views and URL manipulation capabilities.
* *
* @see `Route`. * @see `Route`.
* @see [Routing and Navigation Guide](guide/router). * @see [Routing and Navigation Guide](guide/router).
@ -941,7 +979,7 @@ export class Router {
} }
/** /**
* Resets the configuration used for navigation and generating links. * Resets the route configuration used for navigation and generating links.
* *
* @param config The route array for the new configuration. * @param config The route array for the new configuration.
* *
@ -977,14 +1015,15 @@ export class Router {
} }
/** /**
* Applies an array of commands to the current URL tree and creates a new URL tree. * Appends URL segments to the current URL tree to create a new URL tree.
* *
* When given an activated route, applies the given commands starting from the route. * @param commands An array of URL fragments with which to construct the new URL tree.
* Otherwise, applies the given command starting from the root. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
* * segments, followed by the parameters for each segment.
* @param commands An array of commands to apply. * The fragments are applied to the current URL tree or the one provided in the `relativeTo`
* property of the options object, if supplied.
* @param navigationExtras Options that control the navigation strategy. This function * @param navigationExtras Options that control the navigation strategy. This function
* only utilizes properties in `NavigationExtras` that would change the provided URL. * only uses properties in `NavigationExtras` that would change the provided URL.
* @returns The new URL tree. * @returns The new URL tree.
* *
* @usageNotes * @usageNotes
@ -1057,9 +1096,10 @@ export class Router {
} }
/** /**
* Navigate based on the provided URL, which must be absolute. * Navigates to a view using an absolute route path.
* *
* @param url An absolute URL. The function does not apply any delta to the current URL. * @param url An absolute path for a defined route. The function does not apply any delta to the
* current URL.
* @param extras An object containing properties that modify the navigation strategy. * @param extras An object containing properties that modify the navigation strategy.
* The function ignores any properties in the `NavigationExtras` that would change the * The function ignores any properties in the `NavigationExtras` that would change the
* provided URL. * provided URL.
@ -1069,6 +1109,8 @@ export class Router {
* *
* @usageNotes * @usageNotes
* *
* The following calls request navigation to an absolute path.
*
* ``` * ```
* router.navigateByUrl("/team/33/user/11"); * router.navigateByUrl("/team/33/user/11");
* *
@ -1076,6 +1118,8 @@ export class Router {
* router.navigateByUrl("/team/33/user/11", { skipLocationChange: true }); * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
* ``` * ```
* *
* @see [Routing and Navigation guide](guide/router)
*
*/ */
navigateByUrl(url: string|UrlTree, extras: NavigationExtras = {skipLocationChange: false}): navigateByUrl(url: string|UrlTree, extras: NavigationExtras = {skipLocationChange: false}):
Promise<boolean> { Promise<boolean> {
@ -1094,28 +1138,31 @@ export class Router {
* Navigate based on the provided array of commands and a starting point. * Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute. * If no starting route is provided, the navigation is absolute.
* *
* Returns a promise that: * @param commands An array of URL fragments with which to construct the target URL.
* - resolves to 'true' when navigation succeeds, * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
* - resolves to 'false' when navigation fails, * segments, followed by the parameters for each segment.
* - is rejected when an error happens. * The fragments are applied to the current URL or the one provided in the `relativeTo` property
* of the options object, if supplied.
* @param extras An options object that determines how the URL should be constructed or
* interpreted.
*
* @returns A Promise that resolves to `true` when navigation succeeds, to `false` when navigation
* fails,
* or is rejected on error.
* *
* @usageNotes * @usageNotes
* *
* The following calls request navigation to a dynamic route path relative to the current URL.
*
* ``` * ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route}); * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
* *
* // Navigate without updating the URL * // Navigate without updating the URL, overriding the default behavior
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true}); * 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 * @see [Routing and Navigation guide](guide/router)
* 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.
*/ */
navigate(commands: any[], extras: NavigationExtras = {skipLocationChange: false}): navigate(commands: any[], extras: NavigationExtras = {skipLocationChange: false}):
Promise<boolean> { Promise<boolean> {

View File

@ -71,53 +71,23 @@ export function routerNgProbeToken() {
} }
/** /**
* @usageNotes
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* @NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @description * @description
* *
* Adds router directives and providers. * Adds directives and providers for in-app navigation among views defined in an application.
* Use the Angular `Router` service to declaratively specify application states and manage state
* transitions.
* *
* Managing state transitions is one of the hardest parts of building applications. This is * You can import this NgModule multiple times, once for each lazy-loaded bundle.
* especially true on the web, where you also need to ensure that the state is reflected in the URL. * However, only one `Router` service can be active.
* In addition, we often want to split applications into multiple bundles and load them on demand. * To ensure this, there are two ways to register routes when importing this module:
* Doing this transparently is not trivial.
* *
* The Angular router service solves these problems. Using the router, you can declaratively specify * * The `forRoot()` method creates an `NgModule` that contains all the directives, the given
* application states, manage state transitions while taking care of the URL, and load bundles on * routes, and the `Router` service itself.
* demand. * * The `forChild()` method creates an `NgModule` that contains all the directives and the given
* routes, but does not include the `Router` service.
* *
* @see [Routing and Navigation](guide/router.html) for an * @see [Routing and Navigation guide](guide/router) for an
* overview of how the router service should be used. * overview of how the `Router` service should be used.
* *
* @publicApi * @publicApi
*/ */
@ -134,9 +104,19 @@ export class RouterModule {
* Creates and configures a module with all the router providers and directives. * Creates and configures a module with all the router providers and directives.
* Optionally sets up an application listener to perform an initial navigation. * Optionally sets up an application listener to perform an initial navigation.
* *
* When registering the NgModule at the root, import as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @param routes An array of `Route` objects that define the navigation paths for the application. * @param routes An array of `Route` objects that define the navigation paths for the application.
* @param config An `ExtraOptions` configuration object that controls how navigation is performed. * @param config An `ExtraOptions` configuration object that controls how navigation is performed.
* @return The new router module. * @return The new `NgModule`.
*
*/ */
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule> { static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule> {
return { return {
@ -173,7 +153,20 @@ export class RouterModule {
} }
/** /**
* Creates a module with all the router directives and a provider registering routes. * Creates a module with all the router directives and a provider registering routes,
* without creating a new Router service.
* When registering for submodules and lazy-loaded submodules, create the NgModule as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @param routes An array of `Route` objects that define the navigation paths for the submodule.
* @return The new NgModule.
*
*/ */
static forChild(routes: Routes): ModuleWithProviders<RouterModule> { static forChild(routes: Routes): ModuleWithProviders<RouterModule> {
return {ngModule: RouterModule, providers: [provideRoutes(routes)]}; return {ngModule: RouterModule, providers: [provideRoutes(routes)]};
@ -236,13 +229,17 @@ export function provideRoutes(routes: Routes): any {
* the root component gets created. Use if there is a reason to have * the root component gets created. Use if there is a reason to have
* more control over when the router starts its initial navigation due to some complex * more control over when the router starts its initial navigation due to some complex
* initialization logic. * initialization logic.
*
* The following values have been [deprecated](guide/releases#deprecation-practices) since v4,
* and should not be used for new applications.
*
* * 'legacy_enabled'- (Default, for compatibility.) The initial navigation starts after the root * * 'legacy_enabled'- (Default, for compatibility.) The initial navigation starts after the root
* component has been created. The bootstrap is not blocked until the initial navigation is * component has been created. The bootstrap is not blocked until the initial navigation is
* complete. @deprecated * complete.
* * 'legacy_disabled'- The initial navigation is not performed. The location listener is set up * * 'legacy_disabled'- The initial navigation is not performed. The location listener is set up
* after the root component gets created. @deprecated since v4 * after the root component gets created.
* * `true` - same as 'legacy_enabled'. @deprecated since v4 * * `true` - same as 'legacy_enabled'.
* * `false` - same as 'legacy_disabled'. @deprecated since v4 * * `false` - same as 'legacy_disabled'.
* *
* The 'legacy_enabled' and 'legacy_disabled' should not be used for new applications. * The 'legacy_enabled' and 'legacy_disabled' should not be used for new applications.
* *
@ -256,6 +253,9 @@ export type InitialNavigation = true|false|'enabled'|'disabled'|'legacy_enabled'
* A set of configuration options for a router module, provided in the * A set of configuration options for a router module, provided in the
* `forRoot()` method. * `forRoot()` method.
* *
* @see `forRoot()`
*
*
* @publicApi * @publicApi
*/ */
export interface ExtraOptions { export interface ExtraOptions {
@ -295,6 +295,9 @@ export interface ExtraOptions {
/** /**
* A custom error handler for failed navigations. * A custom error handler for failed navigations.
* If the handler returns a value, the navigation Promise is resolved with this value.
* If the handler throws an exception, the navigation Promise is rejected with the exception.
*
*/ */
errorHandler?: ErrorHandler; errorHandler?: ErrorHandler;

View File

@ -28,7 +28,8 @@ import {Tree, TreeNode} from './utils/tree';
* and the resolved data. * and the resolved data.
* Use the `ActivatedRoute` properties to traverse the tree from any node. * Use the `ActivatedRoute` properties to traverse the tree from any node.
* *
* ### Example * The following fragment shows how a component gets the root node
* of the current state to establish its own route tree:
* *
* ``` * ```
* @Component({templateUrl:'template.html'}) * @Component({templateUrl:'template.html'})
@ -44,6 +45,7 @@ import {Tree, TreeNode} from './utils/tree';
* ``` * ```
* *
* @see `ActivatedRoute` * @see `ActivatedRoute`
* @see [Getting route information](guide/router#getting-route-information)
* *
* @publicApi * @publicApi
*/ */
@ -93,9 +95,14 @@ export function createEmptyStateSnapshot(
* that is loaded in an outlet. * that is loaded in an outlet.
* Use to traverse the `RouterState` tree and extract information from nodes. * Use to traverse the `RouterState` tree and extract information from nodes.
* *
* The following example shows how to construct a component using information from a
* currently activated route.
*
* {@example router/activated-route/module.ts region="activated-route" * {@example router/activated-route/module.ts region="activated-route"
* header="activated-route.component.ts"} * header="activated-route.component.ts"}
* *
* @see [Getting route information](guide/router#getting-route-information)
*
* @publicApi * @publicApi
*/ */
export class ActivatedRoute { export class ActivatedRoute {
@ -249,6 +256,9 @@ function flattenInherited(pathFromRoot: ActivatedRouteSnapshot[]): Inherited {
* outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to
* traverse the router state tree. * traverse the router state tree.
* *
* The following example initializes a component with route information extracted
* from the snapshot of the root node at the time of creation.
*
* ``` * ```
* @Component({templateUrl:'./my-component.html'}) * @Component({templateUrl:'./my-component.html'})
* class MyComponent { * class MyComponent {
@ -361,8 +371,8 @@ export class ActivatedRouteSnapshot {
* This is a tree of activated route snapshots. Every node in this tree knows about * This is a tree of activated route snapshots. Every node in this tree knows about
* the "consumed" URL segments, the extracted parameters, and the resolved data. * the "consumed" URL segments, the extracted parameters, and the resolved data.
* *
* @usageNotes * The following example shows how a component is initialized with information
* ### Example * from the snapshot of the root node's state at the time of creation.
* *
* ``` * ```
* @Component({templateUrl:'template.html'}) * @Component({templateUrl:'template.html'})