chore(routing): update routing package

This commit is contained in:
Dan Bucholtz
2018-02-06 00:13:41 -06:00
parent f1719cd8d0
commit 97baabde93
96 changed files with 39228 additions and 346 deletions

View File

@ -0,0 +1,18 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injector } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Routes } from './config';
import { RouterConfigLoader } from './router_config_loader';
import { UrlSerializer, UrlTree } from './url_tree';
/**
* Returns the `UrlTree` with the redirection applied.
*
* Lazy modules are loaded along the way.
*/
export declare function applyRedirects(moduleInjector: Injector, configLoader: RouterConfigLoader, urlSerializer: UrlSerializer, urlTree: UrlTree, config: Routes): Observable<UrlTree>;

View File

@ -0,0 +1,354 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { NgModuleFactory, NgModuleRef, Type } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { UrlSegment, UrlSegmentGroup } from './url_tree';
/**
* @whatItDoes Represents router configuration.
*
* @description
* `Routes` is an array of route configurations. Each one has the following properties:
*
* - `path` is a string that uses the route matcher DSL.
* - `pathMatch` is a string that specifies the matching strategy.
* - `matcher` defines a custom strategy for path matching and supersedes `path` and `pathMatch`.
* - `component` is a component type.
* - `redirectTo` is the url fragment which will replace the current matched segment.
* - `outlet` is the name of the outlet the component should be placed into.
* - `canActivate` is an array of DI tokens used to look up CanActivate handlers. See
* {@link CanActivate} for more info.
* - `canActivateChild` is an array of DI tokens used to look up CanActivateChild handlers. See
* {@link CanActivateChild} for more info.
* - `canDeactivate` is an array of DI tokens used to look up CanDeactivate handlers. See
* {@link CanDeactivate} for more info.
* - `canLoad` is an array of DI tokens used to look up CanLoad handlers. See
* {@link CanLoad} for more info.
* - `data` is additional data provided to the component via `ActivatedRoute`.
* - `resolve` is a map of DI tokens used to look up data resolvers. See {@link Resolve} for more
* info.
* - `runGuardsAndResolvers` defines when guards and resolvers will be run. By default they run only
* when the matrix parameters of the route change. When set to `paramsOrQueryParamsChange` they
* will also run when query params change. And when set to `always`, they will run every time.
* - `children` is an array of child route definitions.
* - `loadChildren` is a reference to lazy loaded child routes. See {@link LoadChildren} for more
* info.
*
* ### Simple Configuration
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* When navigating to `/team/11/user/bob`, the router will create the team component with the user
* component in it.
*
* ### Multiple Outlets
*
* ```
* [{
* path: 'team/:id',
* component: Team
* }, {
* path: 'chat/:user',
* component: Chat
* outlet: 'aux'
* }]
* ```
*
* When navigating to `/team/11(aux:chat/jim)`, the router will create the team component next to
* the chat component. The chat component will be placed into the aux outlet.
*
* ### Wild Cards
*
* ```
* [{
* path: '**',
* component: Sink
* }]
* ```
*
* Regardless of where you navigate to, the router will instantiate the sink component.
*
* ### Redirects
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: 'legacy/user/:name',
* redirectTo: 'user/:name'
* }, {
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* When navigating to '/team/11/legacy/user/jim', the router will change the url to
* '/team/11/user/jim', and then will instantiate the team component with the user component
* in it.
*
* If the `redirectTo` value starts with a '/', then it is an absolute redirect. E.g., if in the
* example above we change the `redirectTo` to `/user/:name`, the result url will be '/user/jim'.
*
* ### Empty Path
*
* Empty-path route configurations can be used to instantiate components that do not 'consume'
* any url segments. Let's look at the following configuration:
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: '',
* component: AllUsers
* }, {
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* When navigating to `/team/11`, the router will instantiate the AllUsers component.
*
* Empty-path routes can have children.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: '',
* component: WrapperCmp,
* children: [{
* path: 'user/:name',
* component: User
* }]
* }]
* }]
* ```
*
* When navigating to `/team/11/user/jim`, the router will instantiate the wrapper component with
* the user component in it.
*
* An empty path route inherits its parent's params and data. This is because it cannot have its
* own params, and, as a result, it often uses its parent's params and data as its own.
*
* ### Matching Strategy
*
* By default the router will look at what is left in the url, and check if it starts with
* the specified path (e.g., `/team/11/user` starts with `team/:id`).
*
* We can change the matching strategy to make sure that the path covers the whole unconsumed url,
* which is akin to `unconsumedUrl === path` or `$` regular expressions.
*
* This is particularly important when redirecting empty-path routes.
*
* ```
* [{
* path: '',
* pathMatch: 'prefix', //default
* redirectTo: 'main'
* }, {
* path: 'main',
* component: Main
* }]
* ```
*
* Since an empty path is a prefix of any url, even when navigating to '/main', the router will
* still apply the redirect.
*
* If `pathMatch: full` is provided, the router will apply the redirect if and only if navigating to
* '/'.
*
* ```
* [{
* path: '',
* pathMatch: 'full',
* redirectTo: 'main'
* }, {
* path: 'main',
* component: Main
* }]
* ```
*
* ### Componentless Routes
*
* It is useful at times to have the ability to share parameters between sibling components.
*
* Say we have two components--ChildCmp and AuxCmp--that we want to put next to each other and both
* of them require some id parameter.
*
* One way to do that would be to have a bogus parent component, so both the siblings can get the id
* parameter from it. This is not ideal. Instead, you can use a componentless route.
*
* ```
* [{
* path: 'parent/:id',
* children: [
* { path: 'a', component: MainChild },
* { path: 'b', component: AuxChild, outlet: 'aux' }
* ]
* }]
* ```
*
* So when navigating to `parent/10/(a//aux:b)`, the route will instantiate the main child and aux
* child components next to each other. In this example, the application component
* has to have the primary and aux outlets defined.
*
* The router will also merge the `params`, `data`, and `resolve` of the componentless parent into
* the `params`, `data`, and `resolve` of the children. This is done because there is no component
* that can inject the activated route of the componentless parent.
*
* This is especially useful when child components are defined as follows:
*
* ```
* [{
* path: 'parent/:id',
* children: [
* { path: '', component: MainChild },
* { path: '', component: AuxChild, outlet: 'aux' }
* ]
* }]
* ```
*
* With this configuration in place, navigating to '/parent/10' will create the main child and aux
* components.
*
* ### Lazy Loading
*
* Lazy loading speeds up our application load time by splitting it into multiple bundles, and
* loading them on demand. The router is designed to make lazy loading simple and easy. Instead of
* providing the children property, you can provide the `loadChildren` property, as follows:
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* loadChildren: 'team'
* }]
* ```
*
* The router will use registered NgModuleFactoryLoader to fetch an NgModule associated with 'team'.
* Then it will extract the set of routes defined in that NgModule, and will transparently add
* those routes to the main configuration.
*
* @stable use Routes
*/
export declare type Routes = Route[];
/**
* @whatItDoes Represents the results of the URL matching.
*
* * `consumed` is an array of the consumed URL segments.
* * `posParams` is a map of positional parameters.
*
* @experimental
*/
export declare type UrlMatchResult = {
consumed: UrlSegment[];
posParams?: {
[name: string]: UrlSegment;
};
};
/**
* @whatItDoes A function matching URLs
*
* @description
*
* A custom URL matcher can be provided when a combination of `path` and `pathMatch` isn't
* expressive enough.
*
* For instance, the following matcher matches html files.
*
* ```
* export function htmlFiles(url: UrlSegment[]) {
* return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null;
* }
*
* export const routes = [{ matcher: htmlFiles, component: AnyComponent }];
* ```
*
* @experimental
*/
export declare type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => UrlMatchResult;
/**
* @whatItDoes Represents the static data associated with a particular route.
* See {@link Routes} for more details.
* @stable
*/
export declare type Data = {
[name: string]: any;
};
/**
* @whatItDoes Represents the resolved data associated with a particular route.
* See {@link Routes} for more details.
* @stable
*/
export declare type ResolveData = {
[name: string]: any;
};
/**
* @whatItDoes The type of `loadChildren`.
* See {@link Routes} for more details.
* @stable
*/
export declare type LoadChildrenCallback = () => Type<any> | NgModuleFactory<any> | Promise<Type<any>> | Observable<Type<any>>;
/**
* @whatItDoes The type of `loadChildren`.
* See {@link Routes} for more details.
* @stable
*/
export declare type LoadChildren = string | LoadChildrenCallback;
/**
* @whatItDoes The type of `queryParamsHandling`.
* See {@link RouterLink} for more details.
* @stable
*/
export declare type QueryParamsHandling = 'merge' | 'preserve' | '';
/**
* @whatItDoes The type of `runGuardsAndResolvers`.
* See {@link Routes} for more details.
* @experimental
*/
export declare type RunGuardsAndResolvers = 'paramsChange' | 'paramsOrQueryParamsChange' | 'always';
/**
* See {@link Routes} for more details.
* @stable
*/
export interface Route {
path?: string;
pathMatch?: string;
matcher?: UrlMatcher;
component?: Type<any>;
redirectTo?: string;
outlet?: string;
canActivate?: any[];
canActivateChild?: any[];
canDeactivate?: any[];
canLoad?: any[];
data?: Data;
resolve?: ResolveData;
children?: Routes;
loadChildren?: LoadChildren;
runGuardsAndResolvers?: RunGuardsAndResolvers;
}
export declare class LoadedRouterConfig {
routes: Route[];
module: NgModuleRef<any>;
constructor(routes: Route[], module: NgModuleRef<any>);
}
export declare function validateConfig(config: Routes, parentPath?: string): void;

View File

@ -0,0 +1,3 @@
import { RouteReuseStrategy } from './route_reuse_strategy';
import { RouterState, RouterStateSnapshot } from './router_state';
export declare function createRouterState(routeReuseStrategy: RouteReuseStrategy, curr: RouterStateSnapshot, prevState: RouterState): RouterState;

View File

@ -0,0 +1,11 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ActivatedRoute } from './router_state';
import { Params } from './shared';
import { UrlTree } from './url_tree';
export declare function createUrlTree(route: ActivatedRoute, urlTree: UrlTree, commands: any[], queryParams: Params, fragment: string): UrlTree;

View File

@ -0,0 +1,149 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { LocationStrategy } from '@angular/common';
import { ElementRef, OnChanges, OnDestroy, Renderer2 } from '@angular/core';
import { QueryParamsHandling } from '../config';
import { Router } from '../router';
import { ActivatedRoute } from '../router_state';
import { UrlTree } from '../url_tree';
/**
* @whatItDoes Lets you link to specific parts of your app.
*
* @howToUse
*
* Consider the following route configuration:
* `[{ path: 'user/:name', component: UserCmp }]`
*
* When linking to this `user/:name` route, you can write:
* `<a routerLink='/user/bob'>link to user component</a>`
*
* @description
*
* The RouterLink directives let you link to specific parts of your app.
*
* When the link is static, you can use the directive as follows:
* `<a routerLink="/user/bob">link to user component</a>`
*
* If you use dynamic values to generate the link, you can pass an array of path
* segments, followed by the params for each segment.
*
* For instance `['/team', teamId, 'user', userName, {details: true}]`
* means that we want to generate a link to `/team/11/user/bob;details=true`.
*
* Multiple static segments can be merged into one
* (e.g., `['/team/11/user', userName, {details: true}]`).
*
* The first segment name can be prepended with `/`, `./`, or `../`:
* * If the first segment begins with `/`, the router will look up the route from the root of the
* app.
* * If the first segment begins with `./`, or doesn't begin with a slash, the router will
* instead look in the children of the current activated route.
* * And if the first segment begins with `../`, the router will go up one level.
*
* You can set query params and fragment as follows:
*
* ```
* <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
* link to user component
* </a>
* ```
* RouterLink will use these to generate this link: `/user/bob#education?debug=true`.
*
* (Deprecated in v4.0.0 use `queryParamsHandling` instead) You can also tell the
* directive to preserve the current query params and fragment:
*
* ```
* <a [routerLink]="['/user/bob']" preserveQueryParams preserveFragment>
* link to user component
* </a>
* ```
*
* You can tell the directive to how to handle queryParams, available options are:
* - `'merge'`: merge the queryParams into the current queryParams
* - `'preserve'`: preserve the current queryParams
* - default/`''`: use the queryParams only
*
* Same options for {@link NavigationExtras#queryParamsHandling
* NavigationExtras#queryParamsHandling}.
*
* ```
* <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
* link to user component
* </a>
* ```
*
* The router link directive always treats the provided input as a delta to the current url.
*
* For instance, if the current url is `/user/(box//aux:team)`.
*
* Then the following link `<a [routerLink]="['/user/jim']">Jim</a>` will generate the link
* `/user/(jim//aux:team)`.
*
* See {@link Router#createUrlTree createUrlTree} for more information.
*
* @ngModule RouterModule
*
* @stable
*/
export declare class RouterLink {
private router;
private route;
queryParams: {
[k: string]: any;
};
fragment: string;
queryParamsHandling: QueryParamsHandling;
preserveFragment: boolean;
skipLocationChange: boolean;
replaceUrl: boolean;
private commands;
private preserve;
constructor(router: Router, route: ActivatedRoute, tabIndex: string, renderer: Renderer2, el: ElementRef);
routerLink: any[] | string;
/**
* @deprecated 4.0.0 use `queryParamsHandling` instead.
*/
preserveQueryParams: boolean;
onClick(): boolean;
readonly urlTree: UrlTree;
}
/**
* @whatItDoes Lets you link to specific parts of your app.
*
* See {@link RouterLink} for more information.
*
* @ngModule RouterModule
*
* @stable
*/
export declare class RouterLinkWithHref implements OnChanges, OnDestroy {
private router;
private route;
private locationStrategy;
target: string;
queryParams: {
[k: string]: any;
};
fragment: string;
queryParamsHandling: QueryParamsHandling;
preserveFragment: boolean;
skipLocationChange: boolean;
replaceUrl: boolean;
private commands;
private subscription;
private preserve;
href: string;
constructor(router: Router, route: ActivatedRoute, locationStrategy: LocationStrategy);
routerLink: any[] | string;
preserveQueryParams: boolean;
ngOnChanges(changes: {}): any;
ngOnDestroy(): any;
onClick(button: number, ctrlKey: boolean, metaKey: boolean, shiftKey: boolean): boolean;
private updateTargetUrlAndHref();
readonly urlTree: UrlTree;
}

View File

@ -0,0 +1,94 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { AfterContentInit, ChangeDetectorRef, ElementRef, OnChanges, OnDestroy, QueryList, Renderer2, SimpleChanges } from '@angular/core';
import { Router } from '../router';
import { RouterLink, RouterLinkWithHref } from './router_link';
/**
* @whatItDoes Lets you add a CSS class to an element when the link's route becomes active.
*
* @howToUse
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
* ```
*
* @description
*
* The RouterLinkActive directive lets you add a CSS class to an element when the link's route
* becomes active.
*
* Consider the following example:
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
* ```
*
* When the url is either '/user' or '/user/bob', the active-link class will
* be added to the `a` tag. If the url changes, the class will be removed.
*
* You can set more than one class, as follows:
*
* ```
* <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
* <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
* ```
*
* You can configure RouterLinkActive by passing `exact: true`. This will add the classes
* only when the url matches the link exactly.
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
* true}">Bob</a>
* ```
*
* You can assign the RouterLinkActive instance to a template variable and directly check
* the `isActive` status.
* ```
* <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
* Bob {{ rla.isActive ? '(already open)' : ''}}
* </a>
* ```
*
* Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink.
*
* ```
* <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
* <a routerLink="/user/jim">Jim</a>
* <a routerLink="/user/bob">Bob</a>
* </div>
* ```
*
* This will set the active-link class on the div tag if the url is either '/user/jim' or
* '/user/bob'.
*
* @ngModule RouterModule
*
* @stable
*/
export declare class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit {
private router;
private element;
private renderer;
private cdr;
links: QueryList<RouterLink>;
linksWithHrefs: QueryList<RouterLinkWithHref>;
private classes;
private subscription;
readonly isActive: boolean;
routerLinkActiveOptions: {
exact: boolean;
};
constructor(router: Router, element: ElementRef, renderer: Renderer2, cdr: ChangeDetectorRef);
ngAfterContentInit(): void;
routerLinkActive: string[] | string;
ngOnChanges(changes: SimpleChanges): void;
ngOnDestroy(): void;
private update();
private isLinkActive(router);
private hasActiveLinks();
}

View File

@ -0,0 +1,64 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ChangeDetectorRef, ComponentFactoryResolver, ComponentRef, EventEmitter, OnDestroy, OnInit, ViewContainerRef } from '@angular/core';
import { ChildrenOutletContexts } from '../router_outlet_context';
import { ActivatedRoute } from '../router_state';
/**
* @whatItDoes Acts as a placeholder that Angular dynamically fills based on the current router
* state.
*
* @howToUse
*
* ```
* <router-outlet></router-outlet>
* <router-outlet name='left'></router-outlet>
* <router-outlet name='right'></router-outlet>
* ```
*
* A router outlet will emit an activate event any time a new component is being instantiated,
* and a deactivate event when it is being destroyed.
*
* ```
* <router-outlet
* (activate)='onActivate($event)'
* (deactivate)='onDeactivate($event)'></router-outlet>
* ```
* @ngModule RouterModule
*
* @stable
*/
export declare class RouterOutlet implements OnDestroy, OnInit {
private parentContexts;
private location;
private resolver;
private changeDetector;
private activated;
private _activatedRoute;
private name;
activateEvents: EventEmitter<any>;
deactivateEvents: EventEmitter<any>;
constructor(parentContexts: ChildrenOutletContexts, location: ViewContainerRef, resolver: ComponentFactoryResolver, name: string, changeDetector: ChangeDetectorRef);
ngOnDestroy(): void;
ngOnInit(): void;
readonly isActivated: boolean;
readonly component: Object;
readonly activatedRoute: ActivatedRoute;
readonly activatedRouteData: {
[name: string]: any;
};
/**
* Called when the `RouteReuseStrategy` instructs to detach the subtree
*/
detach(): ComponentRef<any>;
/**
* Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree
*/
attach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute): void;
deactivate(): void;
activateWith(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver | null): void;
}

View File

@ -0,0 +1,365 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Route } from './config';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from './router_state';
/**
* @whatItDoes Identifies the trigger of the navigation.
*
* * 'imperative'--triggered by `router.navigateByUrl` or `router.navigate`.
* * 'popstate'--triggered by a popstate event
* * 'hashchange'--triggered by a hashchange event
*
* @experimental
*/
export declare type NavigationTrigger = 'imperative' | 'popstate' | 'hashchange';
/**
* @whatItDoes Base for events the Router goes through, as opposed to events tied to a specific
* Route. `RouterEvent`s will only be fired one time for any given navigation.
*
* Example:
*
* ```
* class MyService {
* constructor(public router: Router, logger: Logger) {
* router.events.filter(e => e instanceof RouterEvent).subscribe(e => {
* logger.log(e.id, e.url);
* });
* }
* }
* ```
*
* @experimental
*/
export declare class RouterEvent {
/** @docsNotRequired */
id: number;
/** @docsNotRequired */
url: string;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string);
}
/**
* @whatItDoes Represents an event triggered when a navigation starts.
*
* @stable
*/
export declare class NavigationStart extends RouterEvent {
/**
* Identifies the trigger of the navigation.
*
* * 'imperative'--triggered by `router.navigateByUrl` or `router.navigate`.
* * 'popstate'--triggered by a popstate event
* * 'hashchange'--triggered by a hashchange event
*/
navigationTrigger?: 'imperative' | 'popstate' | 'hashchange';
/**
* This contains the navigation id that pushed the history record that the router navigates
* back to. This is not null only when the navigation is triggered by a popstate event.
*
* The router assigns a navigationId to every router transition/navigation. Even when the user
* clicks on the back button in the browser, a new navigation id will be created. So from
* the perspective of the router, the router never "goes back". By using the `restoredState`
* and its navigationId, you can implement behavior that differentiates between creating new
* states
* and popstate events. In the latter case you can restore some remembered state (e.g., scroll
* position).
*/
restoredState?: {
navigationId: number;
} | null;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
navigationTrigger?: 'imperative' | 'popstate' | 'hashchange',
/** @docsNotRequired */
restoredState?: {
navigationId: number;
} | null);
/** @docsNotRequired */
toString(): string;
}
/**
* @whatItDoes Represents an event triggered when a navigation ends successfully.
*
* @stable
*/
export declare class NavigationEnd extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string);
/** @docsNotRequired */
toString(): string;
}
/**
* @whatItDoes Represents an event triggered when a navigation is canceled.
*
* @stable
*/
export declare class NavigationCancel extends RouterEvent {
/** @docsNotRequired */
reason: string;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
reason: string);
/** @docsNotRequired */
toString(): string;
}
/**
* @whatItDoes Represents an event triggered when a navigation fails due to an unexpected error.
*
* @stable
*/
export declare class NavigationError extends RouterEvent {
/** @docsNotRequired */
error: any;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
error: any);
/** @docsNotRequired */
toString(): string;
}
/**
* @whatItDoes Represents an event triggered when routes are recognized.
*
* @stable
*/
export declare class RoutesRecognized extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
/** @docsNotRequired */
state: RouterStateSnapshot;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string,
/** @docsNotRequired */
state: RouterStateSnapshot);
/** @docsNotRequired */
toString(): string;
}
/**
* @whatItDoes Represents the start of the Guard phase of routing.
*
* @experimental
*/
export declare class GuardsCheckStart extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
/** @docsNotRequired */
state: RouterStateSnapshot;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string,
/** @docsNotRequired */
state: RouterStateSnapshot);
toString(): string;
}
/**
* @whatItDoes Represents the end of the Guard phase of routing.
*
* @experimental
*/
export declare class GuardsCheckEnd extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
/** @docsNotRequired */
state: RouterStateSnapshot;
/** @docsNotRequired */
shouldActivate: boolean;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string,
/** @docsNotRequired */
state: RouterStateSnapshot,
/** @docsNotRequired */
shouldActivate: boolean);
toString(): string;
}
/**
* @whatItDoes Represents the start of the Resolve phase of routing. The timing of this
* event may change, thus it's experimental. In the current iteration it will run
* in the "resolve" phase whether there's things to resolve or not. In the future this
* behavior may change to only run when there are things to be resolved.
*
* @experimental
*/
export declare class ResolveStart extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
/** @docsNotRequired */
state: RouterStateSnapshot;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string,
/** @docsNotRequired */
state: RouterStateSnapshot);
toString(): string;
}
/**
* @whatItDoes Represents the end of the Resolve phase of routing. See note on
* {@link ResolveStart} for use of this experimental API.
*
* @experimental
*/
export declare class ResolveEnd extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
/** @docsNotRequired */
state: RouterStateSnapshot;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string,
/** @docsNotRequired */
state: RouterStateSnapshot);
toString(): string;
}
/**
* @whatItDoes Represents an event triggered before lazy loading a route config.
*
* @experimental
*/
export declare class RouteConfigLoadStart {
/** @docsNotRequired */
route: Route;
constructor(
/** @docsNotRequired */
route: Route);
toString(): string;
}
/**
* @whatItDoes Represents an event triggered when a route has been lazy loaded.
*
* @experimental
*/
export declare class RouteConfigLoadEnd {
/** @docsNotRequired */
route: Route;
constructor(
/** @docsNotRequired */
route: Route);
toString(): string;
}
/**
* @whatItDoes Represents the start of end of the Resolve phase of routing. See note on
* {@link ChildActivationEnd} for use of this experimental API.
*
* @experimental
*/
export declare class ChildActivationStart {
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot;
constructor(
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
/**
* @whatItDoes Represents the start of end of the Resolve phase of routing. See note on
* {@link ChildActivationStart} for use of this experimental API.
*
* @experimental
*/
export declare class ChildActivationEnd {
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot;
constructor(
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
/**
* @whatItDoes Represents the start of end of the Resolve phase of routing. See note on
* {@link ActivationEnd} for use of this experimental API.
*
* @experimental
*/
export declare class ActivationStart {
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot;
constructor(
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
/**
* @whatItDoes Represents the start of end of the Resolve phase of routing. See note on
* {@link ActivationStart} for use of this experimental API.
*
* @experimental
*/
export declare class ActivationEnd {
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot;
constructor(
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
/**
* @whatItDoes Represents a router event, allowing you to track the lifecycle of the router.
*
* The sequence of router events is:
*
* - {@link NavigationStart},
* - {@link RouteConfigLoadStart},
* - {@link RouteConfigLoadEnd},
* - {@link RoutesRecognized},
* - {@link GuardsCheckStart},
* - {@link ChildActivationStart},
* - {@link ActivationStart},
* - {@link GuardsCheckEnd},
* - {@link ResolveStart},
* - {@link ResolveEnd},
* - {@link ActivationEnd}
* - {@link ChildActivationEnd}
* - {@link NavigationEnd},
* - {@link NavigationCancel},
* - {@link NavigationError}
*
* @stable
*/
export declare type Event = RouterEvent | RouteConfigLoadStart | RouteConfigLoadEnd | ChildActivationStart | ChildActivationEnd | ActivationStart | ActivationEnd;

View File

@ -0,0 +1,25 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { Data, LoadChildren, LoadChildrenCallback, ResolveData, Route, Routes, RunGuardsAndResolvers, UrlMatchResult, UrlMatcher } from './config';
export { RouterLink, RouterLinkWithHref } from './directives/router_link';
export { RouterLinkActive } from './directives/router_link_active';
export { RouterOutlet } from './directives/router_outlet';
export { ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, Event, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouterEvent, RoutesRecognized } from './events';
export { CanActivate, CanActivateChild, CanDeactivate, CanLoad, Resolve } from './interfaces';
export { DetachedRouteHandle, RouteReuseStrategy } from './route_reuse_strategy';
export { NavigationExtras, Router } from './router';
export { ROUTES } from './router_config_loader';
export { ExtraOptions, ROUTER_CONFIGURATION, ROUTER_INITIALIZER, RouterModule, provideRoutes } from './router_module';
export { ChildrenOutletContexts, OutletContext } from './router_outlet_context';
export { NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader } from './router_preloader';
export { ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from './router_state';
export { PRIMARY_OUTLET, ParamMap, Params, convertToParamMap } from './shared';
export { UrlHandlingStrategy } from './url_handling_strategy';
export { DefaultUrlSerializer, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree } from './url_tree';
export { VERSION } from './version';
export * from './private_export';

View File

@ -0,0 +1,368 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Observable } from 'rxjs/Observable';
import { Route } from './config';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from './router_state';
/**
* @whatItDoes Interface that a class can implement to be a guard deciding if a route can be
* activated.
*
* @howToUse
*
* ```
* class UserToken {}
* class Permissions {
* canActivate(user: UserToken, id: string): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanActivateTeam implements CanActivate {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canActivate(
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot
* ): Observable<boolean>|Promise<boolean>|boolean {
* return this.permissions.canActivate(this.currentUser, route.params.id);
* }
* }
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamCmp,
* canActivate: [CanActivateTeam]
* }
* ])
* ],
* providers: [CanActivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* You can alternatively provide a function with the `canActivate` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamCmp,
* canActivate: ['canActivateTeam']
* }
* ])
* ],
* providers: [
* {
* provide: 'canActivateTeam',
* useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true
* }
* ]
* })
* class AppModule {}
* ```
*
* @stable
*/
export interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean;
}
/**
* @whatItDoes Interface that a class can implement to be a guard deciding if a child route can be
* activated.
*
* @howToUse
*
* ```
* class UserToken {}
* class Permissions {
* canActivate(user: UserToken, id: string): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanActivateTeam implements CanActivateChild {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canActivateChild(
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot
* ): Observable<boolean>|Promise<boolean>|boolean {
* return this.permissions.canActivate(this.currentUser, route.params.id);
* }
* }
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'root',
* canActivateChild: [CanActivateTeam],
* children: [
* {
* path: 'team/:id',
* component: Team
* }
* ]
* }
* ])
* ],
* providers: [CanActivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* You can alternatively provide a function with the `canActivateChild` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'root',
* canActivateChild: ['canActivateTeam'],
* children: [
* {
* path: 'team/:id',
* component: Team
* }
* ]
* }
* ])
* ],
* providers: [
* {
* provide: 'canActivateTeam',
* useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true
* }
* ]
* })
* class AppModule {}
* ```
*
* @stable
*/
export interface CanActivateChild {
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean;
}
/**
* @whatItDoes Interface that a class can implement to be a guard deciding if a route can be
* deactivated.
*
* @howToUse
*
* ```
* class UserToken {}
* class Permissions {
* canDeactivate(user: UserToken, id: string): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanDeactivateTeam implements CanDeactivate<TeamComponent> {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canDeactivate(
* component: TeamComponent,
* currentRoute: ActivatedRouteSnapshot,
* currentState: RouterStateSnapshot,
* nextState: RouterStateSnapshot
* ): Observable<boolean>|Promise<boolean>|boolean {
* return this.permissions.canDeactivate(this.currentUser, route.params.id);
* }
* }
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamCmp,
* canDeactivate: [CanDeactivateTeam]
* }
* ])
* ],
* providers: [CanDeactivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* You can alternatively provide a function with the `canDeactivate` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamCmp,
* canDeactivate: ['canDeactivateTeam']
* }
* ])
* ],
* providers: [
* {
* provide: 'canDeactivateTeam',
* useValue: (component: TeamComponent, currentRoute: ActivatedRouteSnapshot, currentState:
* RouterStateSnapshot, nextState: RouterStateSnapshot) => true
* }
* ]
* })
* class AppModule {}
* ```
*
* @stable
*/
export interface CanDeactivate<T> {
canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean;
}
/**
* @whatItDoes Interface that class can implement to be a data provider.
*
* @howToUse
*
* ```
* class Backend {
* fetchTeam(id: string) {
* return 'someTeam';
* }
* }
*
* @Injectable()
* class TeamResolver implements Resolve<Team> {
* constructor(private backend: Backend) {}
*
* resolve(
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot
* ): Observable<any>|Promise<any>|any {
* return this.backend.fetchTeam(route.params.id);
* }
* }
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamCmp,
* resolve: {
* team: TeamResolver
* }
* }
* ])
* ],
* providers: [TeamResolver]
* })
* class AppModule {}
* ```
*
* You can alternatively provide a function with the `resolve` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamCmp,
* resolve: {
* team: 'teamResolver'
* }
* }
* ])
* ],
* providers: [
* {
* provide: 'teamResolver',
* useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => 'team'
* }
* ]
* })
* class AppModule {}
* ```
* @stable
*/
export interface Resolve<T> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T;
}
/**
* @whatItDoes Interface that a class can implement to be a guard deciding if a children can be
* loaded.
*
* @howToUse
*
* ```
* class UserToken {}
* class Permissions {
* canLoadChildren(user: UserToken, id: string): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanLoadTeamSection implements CanLoad {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canLoad(route: Route): Observable<boolean>|Promise<boolean>|boolean {
* return this.permissions.canLoadChildren(this.currentUser, route);
* }
* }
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamCmp,
* loadChildren: 'team.js',
* canLoad: [CanLoadTeamSection]
* }
* ])
* ],
* providers: [CanLoadTeamSection, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* You can alternatively provide a function with the `canLoad` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamCmp,
* loadChildren: 'team.js',
* canLoad: ['canLoadTeamSection']
* }
* ])
* ],
* providers: [
* {
* provide: 'canLoadTeamSection',
* useValue: (route: Route) => true
* }
* ]
* })
* class AppModule {}
* ```
*
* @stable
*/
export interface CanLoad {
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean;
}

View File

@ -0,0 +1,69 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injector } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Event } from './events';
import { ChildrenOutletContexts } from './router_outlet_context';
import { RouterStateSnapshot } from './router_state';
/**
* This class bundles the actions involved in preactivation of a route.
*/
export declare class PreActivation {
private future;
private curr;
private moduleInjector;
private forwardEvent;
private canActivateChecks;
private canDeactivateChecks;
constructor(future: RouterStateSnapshot, curr: RouterStateSnapshot, moduleInjector: Injector, forwardEvent?: ((evt: Event) => void) | undefined);
initialize(parentContexts: ChildrenOutletContexts): void;
checkGuards(): Observable<boolean>;
resolveData(paramsInheritanceStrategy: 'emptyOnly' | 'always'): Observable<any>;
isDeactivating(): boolean;
isActivating(): boolean;
/**
* Iterates over child routes and calls recursive `setupRouteGuards` to get `this` instance in
* proper state to run `checkGuards()` method.
*/
private setupChildRouteGuards(futureNode, currNode, contexts, futurePath);
/**
* Iterates over child routes and calls recursive `setupRouteGuards` to get `this` instance in
* proper state to run `checkGuards()` method.
*/
private setupRouteGuards(futureNode, currNode, parentContexts, futurePath);
private shouldRunGuardsAndResolvers(curr, future, mode);
private deactivateRouteAndItsChildren(route, context);
private runCanDeactivateChecks();
private runCanActivateChecks();
/**
* This should fire off `ActivationStart` events for each route being activated at this
* level.
* In other words, if you're activating `a` and `b` below, `path` will contain the
* `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
* return
* `true` so checks continue to run.
*/
private fireActivationStart(snapshot);
/**
* This should fire off `ChildActivationStart` events for each route being activated at this
* level.
* In other words, if you're activating `a` and `b` below, `path` will contain the
* `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
* return
* `true` so checks continue to run.
*/
private fireChildActivationStart(snapshot);
private runCanActivate(future);
private runCanActivateChild(path);
private extractCanActivateChild(p);
private runCanDeactivate(component, curr);
private runResolve(future, paramsInheritanceStrategy);
private resolveNode(resolve, future);
private getResolver(injectionToken, future);
private getToken(token, snapshot);
}

View File

@ -0,0 +1,9 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { ROUTER_PROVIDERS as ɵROUTER_PROVIDERS } from './router_module';
export { flatten as ɵflatten } from './utils/collection';

View File

@ -0,0 +1,13 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Type } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Routes } from './config';
import { ParamsInheritanceStrategy, RouterStateSnapshot } from './router_state';
import { UrlTree } from './url_tree';
export declare function recognize(rootComponentType: Type<any> | null, config: Routes, urlTree: UrlTree, url: string, paramsInheritanceStrategy?: ParamsInheritanceStrategy): Observable<RouterStateSnapshot>;

View File

@ -0,0 +1,41 @@
import { ActivatedRouteSnapshot } from './router_state';
/**
* @whatItDoes Represents the detached route tree.
*
* This is an opaque value the router will give to a custom route reuse strategy
* to store and retrieve later on.
*
* @experimental
*/
export declare type DetachedRouteHandle = {};
/**
* @whatItDoes Provides a way to customize when activated routes get reused.
*
* @experimental
*/
export declare abstract class RouteReuseStrategy {
/** Determines if this route (and its subtree) should be detached to be reused later */
abstract shouldDetach(route: ActivatedRouteSnapshot): boolean;
/**
* Stores the detached route.
*
* Storing a `null` value should erase the previously stored value.
*/
abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void;
/** Determines if this route (and its subtree) should be reattached */
abstract shouldAttach(route: ActivatedRouteSnapshot): boolean;
/** Retrieves the previously stored route */
abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;
/** Determines if a route should be reused */
abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
}
/**
* Does not detach any subtrees. Reuses routes as long as their route config is the same.
*/
export declare class DefaultRouteReuseStrategy implements RouteReuseStrategy {
shouldDetach(route: ActivatedRouteSnapshot): boolean;
store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void;
shouldAttach(route: ActivatedRouteSnapshot): boolean;
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
}

View File

@ -0,0 +1,325 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Location } from '@angular/common';
import { Compiler, Injector, NgModuleFactoryLoader, NgModuleRef, Type } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { QueryParamsHandling, Routes } from './config';
import { Event } from './events';
import { RouteReuseStrategy } from './route_reuse_strategy';
import { RouterConfigLoader } from './router_config_loader';
import { ChildrenOutletContexts } from './router_outlet_context';
import { ActivatedRoute, RouterState } from './router_state';
import { Params } from './shared';
import { UrlHandlingStrategy } from './url_handling_strategy';
import { UrlSerializer, UrlTree } from './url_tree';
/**
* @whatItDoes Represents the extra options used during navigation.
*
* @stable
*/
export interface NavigationExtras {
/**
* Enables relative navigation from the current ActivatedRoute.
*
* Configuration:
*
* ```
* [{
* path: 'parent',
* component: ParentComponent,
* children: [{
* path: 'list',
* component: ListComponent
* },{
* path: 'child',
* component: ChildComponent
* }]
* }]
* ```
*
* Navigate to list route from child route:
*
* ```
* @Component({...})
* class ChildComponent {
* constructor(private router: Router, private route: ActivatedRoute) {}
*
* go() {
* this.router.navigate(['../list'], { relativeTo: this.route });
* }
* }
* ```
*/
relativeTo?: ActivatedRoute | null;
/**
* Sets query parameters to the URL.
*
* ```
* // Navigate to /results?page=1
* this.router.navigate(['/results'], { queryParams: { page: 1 } });
* ```
*/
queryParams?: Params | null;
/**
* Sets the hash fragment for the URL.
*
* ```
* // Navigate to /results#top
* this.router.navigate(['/results'], { fragment: 'top' });
* ```
*/
fragment?: string;
/**
* Preserves the query parameters for the next navigation.
*
* deprecated, use `queryParamsHandling` instead
*
* ```
* // Preserve query params from /results?page=1 to /view?page=1
* this.router.navigate(['/view'], { preserveQueryParams: true });
* ```
*
* @deprecated since v4
*/
preserveQueryParams?: boolean;
/**
* config strategy to handle the query parameters for the next navigation.
*
* ```
* // from /results?page=1 to /view?page=1&page=2
* this.router.navigate(['/view'], { queryParams: { page: 2 }, queryParamsHandling: "merge" });
* ```
*/
queryParamsHandling?: QueryParamsHandling | null;
/**
* Preserves the fragment for the next navigation
*
* ```
* // Preserve fragment from /results#top to /view#top
* this.router.navigate(['/view'], { preserveFragment: true });
* ```
*/
preserveFragment?: boolean;
/**
* Navigates without pushing a new state into history.
*
* ```
* // Navigate silently to /view
* this.router.navigate(['/view'], { skipLocationChange: true });
* ```
*/
skipLocationChange?: boolean;
/**
* Navigates while replacing the current state in history.
*
* ```
* // Navigate to /view
* this.router.navigate(['/view'], { replaceUrl: true });
* ```
*/
replaceUrl?: boolean;
}
/**
* @whatItDoes Error handler that is invoked when a navigation errors.
*
* @description
* If the handler returns a value, the navigation promise will be resolved with this value.
* If the handler throws an exception, the navigation promise will be rejected with
* the exception.
*
* @stable
*/
export declare type ErrorHandler = (error: any) => any;
/**
* @whatItDoes Provides the navigation and url manipulation capabilities.
*
* See {@link Routes} for more details and examples.
*
* @ngModule RouterModule
*
* @stable
*/
export declare class Router {
private rootComponentType;
protected urlSerializer: UrlSerializer;
protected rootContexts: ChildrenOutletContexts;
protected location: Location;
config: Routes;
protected currentUrlTree: UrlTree;
protected rawUrlTree: UrlTree;
private navigations;
private locationSubscription;
protected navigationId: number;
protected configLoader: RouterConfigLoader;
protected ngModule: NgModuleRef<any>;
readonly events: Observable<Event>;
readonly routerState: RouterState;
/**
* Error handler that is invoked when a navigation errors.
*
* See {@link ErrorHandler} for more information.
*/
errorHandler: ErrorHandler;
/**
* Indicates if at least one navigation happened.
*/
navigated: boolean;
protected lastSuccessfulId: number;
/**
* Extracts and merges URLs. Used for AngularJS to Angular migrations.
*/
urlHandlingStrategy: UrlHandlingStrategy;
routeReuseStrategy: RouteReuseStrategy;
/**
* Define what the router should do if it receives a navigation request to the current URL.
* By default, the router will ignore this navigation. However, this prevents features such
* as a "refresh" button. Use this option to configure the behavior when navigating to the
* current URL. Default is 'ignore'.
*/
onSameUrlNavigation: 'reload' | 'ignore';
/**
* Defines how the router merges params, data and resolved data from parent to child
* routes. Available options are:
*
* - `'emptyOnly'`, the default, only inherits parent params for path-less or component-less
* routes.
* - `'always'`, enables unconditional inheritance of parent params.
*/
paramsInheritanceStrategy: 'emptyOnly' | 'always';
/**
* Creates the router service.
*/
constructor(rootComponentType: Type<any> | null, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes);
/**
* Sets up the location change listener and performs the initial navigation.
*/
initialNavigation(): void;
/**
* Sets up the location change listener.
*/
setUpLocationChangeListener(): void;
/** The current url */
readonly url: string;
/**
* Resets the configuration used for navigation and generating links.
*
* ### Usage
*
* ```
* router.resetConfig([
* { path: 'team/:id', component: TeamCmp, children: [
* { path: 'simple', component: SimpleCmp },
* { path: 'user/:name', component: UserCmp }
* ]}
* ]);
* ```
*/
resetConfig(config: Routes): void;
/** @docsNotRequired */
ngOnDestroy(): void;
/** Disposes of the router */
dispose(): void;
/**
* Applies an array of commands to the current url tree and creates a 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
*
* ```
* // 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});
* ```
*/
createUrlTree(commands: any[], navigationExtras?: NavigationExtras): UrlTree;
/**
* Navigate based on the provided url. This navigation is always absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigateByUrl("/team/33/user/11");
*
* // Navigate without updating the URL
* router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
* ```
*
* In opposite to `navigate`, `navigateByUrl` takes a whole URL
* and does not apply any delta to the current one.
*/
navigateByUrl(url: string | UrlTree, extras?: NavigationExtras): Promise<boolean>;
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
* URL.
*/
navigate(commands: any[], extras?: NavigationExtras): Promise<boolean>;
/** Serializes a {@link UrlTree} into a string */
serializeUrl(url: UrlTree): string;
/** Parses a string into a {@link UrlTree} */
parseUrl(url: string): UrlTree;
/** Returns whether the url is activated */
isActive(url: string | UrlTree, exact: boolean): boolean;
private removeEmptyProps(params);
private processNavigations();
private scheduleNavigation(rawUrl, source, state, extras);
private executeScheduledNavigation({id, rawUrl, extras, resolve, reject, source, state});
private runNavigate(url, rawUrl, skipLocationChange, replaceUrl, id, precreatedState);
protected resetStateAndUrl(storedState: RouterState, storedUrl: UrlTree, rawUrl: UrlTree): void;
protected resetUrlToCurrentUrlTree(): void;
}

View File

@ -0,0 +1,24 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Compiler, InjectionToken, Injector, NgModuleFactoryLoader } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { LoadedRouterConfig, Route } from './config';
/**
* @docsNotRequired
* @experimental
*/
export declare const ROUTES: InjectionToken<Route[][]>;
export declare class RouterConfigLoader {
private loader;
private compiler;
private onLoadStartListener;
private onLoadEndListener;
constructor(loader: NgModuleFactoryLoader, compiler: Compiler, onLoadStartListener?: ((r: Route) => void) | undefined, onLoadEndListener?: ((r: Route) => void) | undefined);
load(parentInjector: Injector, route: Route): Observable<LoadedRouterConfig>;
private loadModuleFactory(loadChildren);
}

View File

@ -0,0 +1,231 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { HashLocationStrategy, Location, PathLocationStrategy, PlatformLocation } from '@angular/common';
import { ApplicationRef, Compiler, ComponentRef, InjectionToken, Injector, ModuleWithProviders, NgModuleFactoryLoader, NgProbeToken, Provider } from '@angular/core';
import { Route, Routes } from './config';
import { RouteReuseStrategy } from './route_reuse_strategy';
import { ErrorHandler, Router } from './router';
import { ChildrenOutletContexts } from './router_outlet_context';
import { ActivatedRoute } from './router_state';
import { UrlHandlingStrategy } from './url_handling_strategy';
import { UrlSerializer } from './url_tree';
/**
* @whatItDoes Is used in DI to configure the router.
* @stable
*/
export declare const ROUTER_CONFIGURATION: InjectionToken<ExtraOptions>;
/**
* @docsNotRequired
*/
export declare const ROUTER_FORROOT_GUARD: InjectionToken<void>;
export declare const ROUTER_PROVIDERS: Provider[];
export declare function routerNgProbeToken(): NgProbeToken;
/**
* @whatItDoes Adds router directives and providers.
*
* @howToUse
*
* 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
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
* overview of how the router should be used.
*
* @stable
*/
export declare class RouterModule {
constructor(guard: any, router: Router);
/**
* Creates a module with all the router providers and directives. It also optionally sets up an
* application listener to perform an initial navigation.
*
* Options (see {@link ExtraOptions}):
* * `enableTracing` makes the router log all its internal events to the console.
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
* API.
* * `initialNavigation` disables the initial navigation.
* * `errorHandler` provides a custom error handler.
* * `preloadingStrategy` configures a preloading strategy (see {@link PreloadAllModules}).
* * `onSameUrlNavigation` configures how the router handles navigation to the current URL. See
* {@link ExtraOptions} for more details.
*/
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders;
/**
* Creates a module with all the router directives and a provider registering routes.
*/
static forChild(routes: Routes): ModuleWithProviders;
}
export declare function provideLocationStrategy(platformLocationStrategy: PlatformLocation, baseHref: string, options?: ExtraOptions): HashLocationStrategy | PathLocationStrategy;
export declare function provideForRootGuard(router: Router): any;
/**
* @whatItDoes Registers routes.
*
* @howToUse
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @stable
*/
export declare function provideRoutes(routes: Routes): any;
/**
* @whatItDoes Represents an option to configure when the initial navigation is performed.
*
* @description
* * 'enabled' - the initial navigation starts before the root component is created.
* The bootstrap is blocked until the initial navigation is complete.
* * 'disabled' - the initial navigation is not performed. The location listener is set up before
* the root component gets created.
* * 'legacy_enabled'- the initial navigation starts after the root component has been created.
* The bootstrap is not blocked until the initial navigation is complete. @deprecated
* * 'legacy_disabled'- the initial navigation is not performed. The location listener is set up
* after @deprecated
* the root component gets created.
* * `true` - same as 'legacy_enabled'. @deprecated since v4
* * `false` - same as 'legacy_disabled'. @deprecated since v4
*
* The 'enabled' option should be used for applications unless there is a reason to have
* more control over when the router starts its initial navigation due to some complex
* initialization logic. In this case, 'disabled' should be used.
*
* The 'legacy_enabled' and 'legacy_disabled' should not be used for new applications.
*
* @experimental
*/
export declare type InitialNavigation = true | false | 'enabled' | 'disabled' | 'legacy_enabled' | 'legacy_disabled';
/**
* @whatItDoes Represents options to configure the router.
*
* @stable
*/
export interface ExtraOptions {
/**
* Makes the router log all its internal events to the console.
*/
enableTracing?: boolean;
/**
* Enables the location strategy that uses the URL fragment instead of the history API.
*/
useHash?: boolean;
/**
* Disables the initial navigation.
*/
initialNavigation?: InitialNavigation;
/**
* A custom error handler.
*/
errorHandler?: ErrorHandler;
/**
* Configures a preloading strategy. See {@link PreloadAllModules}.
*/
preloadingStrategy?: any;
/**
* Define what the router should do if it receives a navigation request to the current URL.
* By default, the router will ignore this navigation. However, this prevents features such
* as a "refresh" button. Use this option to configure the behavior when navigating to the
* current URL. Default is 'ignore'.
*/
onSameUrlNavigation?: 'reload' | 'ignore';
/**
* Defines how the router merges params, data and resolved data from parent to child
* routes. Available options are:
*
* - `'emptyOnly'`, the default, only inherits parent params for path-less or component-less
* routes.
* - `'always'`, enables unconditional inheritance of parent params.
*/
paramsInheritanceStrategy?: 'emptyOnly' | 'always';
}
export declare function setupRouter(ref: ApplicationRef, urlSerializer: UrlSerializer, contexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[][], opts?: ExtraOptions, urlHandlingStrategy?: UrlHandlingStrategy, routeReuseStrategy?: RouteReuseStrategy): Router;
export declare function rootRoute(router: Router): ActivatedRoute;
/**
* To initialize the router properly we need to do in two steps:
*
* We need to start the navigation in a APP_INITIALIZER to block the bootstrap if
* a resolver or a guards executes asynchronously. Second, we need to actually run
* activation in a BOOTSTRAP_LISTENER. We utilize the afterPreactivation
* hook provided by the router to do that.
*
* The router navigation starts, reaches the point when preactivation is done, and then
* pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener.
*/
export declare class RouterInitializer {
private injector;
private initNavigation;
private resultOfPreactivationDone;
constructor(injector: Injector);
appInitializer(): Promise<any>;
bootstrapListener(bootstrappedComponentRef: ComponentRef<any>): void;
private isLegacyEnabled(opts);
private isLegacyDisabled(opts);
}
export declare function getAppInitializer(r: RouterInitializer): any;
export declare function getBootstrapListener(r: RouterInitializer): any;
/**
* A token for the router initializer that will be called after the app is bootstrapped.
*
* @experimental
*/
export declare const ROUTER_INITIALIZER: InjectionToken<(compRef: ComponentRef<any>) => void>;
export declare function provideRouterInitializer(): (typeof RouterInitializer | {
provide: InjectionToken<(() => void)[]>;
multi: boolean;
useFactory: (r: RouterInitializer) => any;
deps: (typeof RouterInitializer)[];
} | {
provide: InjectionToken<(compRef: ComponentRef<any>) => void>;
useFactory: (r: RouterInitializer) => any;
deps: (typeof RouterInitializer)[];
} | {
provide: InjectionToken<((compRef: ComponentRef<any>) => void)[]>;
multi: boolean;
useExisting: InjectionToken<(compRef: ComponentRef<any>) => void>;
})[];

View File

@ -0,0 +1,46 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ComponentFactoryResolver, ComponentRef } from '@angular/core';
import { RouterOutlet } from './directives/router_outlet';
import { ActivatedRoute } from './router_state';
/**
* Store contextual information about a {@link RouterOutlet}
*
* @stable
*/
export declare class OutletContext {
outlet: RouterOutlet | null;
route: ActivatedRoute | null;
resolver: ComponentFactoryResolver | null;
children: ChildrenOutletContexts;
attachRef: ComponentRef<any> | null;
}
/**
* Store contextual information about the children (= nested) {@link RouterOutlet}
*
* @stable
*/
export declare class ChildrenOutletContexts {
private contexts;
/** Called when a `RouterOutlet` directive is instantiated */
onChildOutletCreated(childName: string, outlet: RouterOutlet): void;
/**
* Called when a `RouterOutlet` directive is destroyed.
* We need to keep the context as the outlet could be destroyed inside a NgIf and might be
* re-created later.
*/
onChildOutletDestroyed(childName: string): void;
/**
* Called when the corresponding route is deactivated during navigation.
* Because the component get destroyed, all children outlet are destroyed.
*/
onOutletDeactivated(): Map<string, OutletContext>;
onOutletReAttached(contexts: Map<string, OutletContext>): void;
getOrCreateContext(childName: string): OutletContext;
getContext(childName: string): OutletContext | null;
}

View File

@ -0,0 +1,70 @@
/**
*@license
*Copyright Google Inc. All Rights Reserved.
*
*Use of this source code is governed by an MIT-style license that can be
*found in the LICENSE file at https://angular.io/license
*/
import { Compiler, Injector, NgModuleFactoryLoader, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Route } from './config';
import { Router } from './router';
/**
* @whatItDoes Provides a preloading strategy.
*
* @experimental
*/
export declare abstract class PreloadingStrategy {
abstract preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
/**
* @whatItDoes Provides a preloading strategy that preloads all modules as quickly as possible.
*
* @howToUse
*
* ```
* RouteModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
* ```
*
* @experimental
*/
export declare class PreloadAllModules implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
/**
* @whatItDoes Provides a preloading strategy that does not preload any modules.
*
* @description
*
* This strategy is enabled by default.
*
* @experimental
*/
export declare class NoPreloading implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
/**
* The preloader optimistically loads all router configurations to
* make navigations into lazily-loaded sections of the application faster.
*
* The preloader runs in the background. When the router bootstraps, the preloader
* starts listening to all navigation events. After every such event, the preloader
* will check if any configurations can be loaded lazily.
*
* If a route is protected by `canLoad` guards, the preloaded will not load it.
*
* @stable
*/
export declare class RouterPreloader implements OnDestroy {
private router;
private injector;
private preloadingStrategy;
private loader;
private subscription;
constructor(router: Router, moduleLoader: NgModuleFactoryLoader, compiler: Compiler, injector: Injector, preloadingStrategy: PreloadingStrategy);
setUpPreloading(): void;
preload(): Observable<any>;
ngOnDestroy(): void;
private processRoutes(ngModule, routes);
private preloadConfig(ngModule, route);
}

View File

@ -0,0 +1,190 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Type } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Data, Route } from './config';
import { ParamMap, Params } from './shared';
import { UrlSegment, UrlTree } from './url_tree';
import { Tree } from './utils/tree';
/**
* @whatItDoes Represents the state of the router.
*
* @howToUse
*
* ```
* @Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const state: RouterState = router.routerState;
* const root: ActivatedRoute = state.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
* }
* }
* ```
*
* @description
* RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL
* segments, the extracted parameters, and the resolved data.
*
* See {@link ActivatedRoute} for more information.
*
* @stable
*/
export declare class RouterState extends Tree<ActivatedRoute> {
/** The current snapshot of the router state */
snapshot: RouterStateSnapshot;
toString(): string;
}
export declare function createEmptyState(urlTree: UrlTree, rootComponent: Type<any> | null): RouterState;
export declare function createEmptyStateSnapshot(urlTree: UrlTree, rootComponent: Type<any> | null): RouterStateSnapshot;
/**
* @whatItDoes Contains the information about a route associated with a component loaded in an
* outlet.
* An `ActivatedRoute` can also be used to traverse the router state tree.
*
* @howToUse
*
* ```
* @Component({...})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: Observable<string> = route.params.map(p => p.id);
* const url: Observable<string> = route.url.map(segments => segments.join(''));
* // route.data includes both `data` and `resolve`
* const user = route.data.map(d => d.user);
* }
* }
* ```
*
* @stable
*/
export declare class ActivatedRoute {
/** An observable of the URL segments matched by this route */
url: Observable<UrlSegment[]>;
/** An observable of the matrix parameters scoped to this route */
params: Observable<Params>;
/** An observable of the query parameters shared by all the routes */
queryParams: Observable<Params>;
/** An observable of the URL fragment shared by all the routes */
fragment: Observable<string>;
/** An observable of the static and resolved data of this route. */
data: Observable<Data>;
/** The outlet name of the route. It's a constant */
outlet: string;
/** The component of the route. It's a constant */
component: Type<any> | string | null;
/** The current snapshot of this route */
snapshot: ActivatedRouteSnapshot;
/** The configuration used to match this route */
readonly routeConfig: Route | null;
/** The root of the router state */
readonly root: ActivatedRoute;
/** The parent of this route in the router state tree */
readonly parent: ActivatedRoute | null;
/** The first child of this route in the router state tree */
readonly firstChild: ActivatedRoute | null;
/** The children of this route in the router state tree */
readonly children: ActivatedRoute[];
/** The path from the root of the router state tree to this route */
readonly pathFromRoot: ActivatedRoute[];
readonly paramMap: Observable<ParamMap>;
readonly queryParamMap: Observable<ParamMap>;
toString(): string;
}
export declare type ParamsInheritanceStrategy = 'emptyOnly' | 'always';
/**
* @whatItDoes Contains the information about a route associated with a component loaded in an
* outlet
* at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router
* state tree.
*
* @howToUse
*
* ```
* @Component({templateUrl:'./my-component.html'})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: string = route.snapshot.params.id;
* const url: string = route.snapshot.url.join('');
* const user = route.snapshot.data.user;
* }
* }
* ```
*
* @stable
*/
export declare class ActivatedRouteSnapshot {
/** The URL segments matched by this route */
url: UrlSegment[];
/** The matrix parameters scoped to this route */
params: Params;
/** The query parameters shared by all the routes */
queryParams: Params;
/** The URL fragment shared by all the routes */
fragment: string;
/** The static and resolved data of this route */
data: Data;
/** The outlet name of the route */
outlet: string;
/** The component of the route */
component: Type<any> | string | null;
/** The configuration used to match this route **/
readonly routeConfig: Route | null;
/** The root of the router state */
readonly root: ActivatedRouteSnapshot;
/** The parent of this route in the router state tree */
readonly parent: ActivatedRouteSnapshot | null;
/** The first child of this route in the router state tree */
readonly firstChild: ActivatedRouteSnapshot | null;
/** The children of this route in the router state tree */
readonly children: ActivatedRouteSnapshot[];
/** The path from the root of the router state tree to this route */
readonly pathFromRoot: ActivatedRouteSnapshot[];
readonly paramMap: ParamMap;
readonly queryParamMap: ParamMap;
toString(): string;
}
/**
* @whatItDoes Represents the state of the router at a moment in time.
*
* @howToUse
*
* ```
* @Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const state: RouterState = router.routerState;
* const snapshot: RouterStateSnapshot = state.snapshot;
* const root: ActivatedRouteSnapshot = snapshot.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
* }
* }
* ```
*
* @description
* RouterStateSnapshot 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.
*
* @stable
*/
export declare class RouterStateSnapshot extends Tree<ActivatedRouteSnapshot> {
/** The url from which this snapshot was created */
url: string;
toString(): string;
}
/**
* The expectation is that the activate route is created with the right set of parameters.
* So we push new values into the observables only when they are not the initial values.
* And we detect that by checking if the snapshot field is set.
*/
export declare function advanceActivatedRoute(route: ActivatedRoute): void;
export declare function equalParamsAndUrlSegments(a: ActivatedRouteSnapshot, b: ActivatedRouteSnapshot): boolean;

View File

@ -0,0 +1,62 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Route, UrlMatchResult } from './config';
import { UrlSegment, UrlSegmentGroup } from './url_tree';
/**
* @whatItDoes Name of the primary outlet.
*
* @stable
*/
export declare const PRIMARY_OUTLET = "primary";
/**
* A collection of parameters.
*
* @stable
*/
export declare type Params = {
[key: string]: any;
};
/**
* Matrix and Query parameters.
*
* `ParamMap` makes it easier to work with parameters as they could have either a single value or
* multiple value. Because this should be known by the user, calling `get` or `getAll` returns the
* correct type (either `string` or `string[]`).
*
* The API is inspired by the URLSearchParams interface.
* see https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
*
* @stable
*/
export interface ParamMap {
has(name: string): boolean;
/**
* Return a single value for the given parameter name:
* - the value when the parameter has a single value,
* - the first value if the parameter has multiple values,
* - `null` when there is no such parameter.
*/
get(name: string): string | null;
/**
* Return an array of values for the given parameter name.
*
* If there is no such parameter, an empty array is returned.
*/
getAll(name: string): string[];
/** Name of the parameters */
readonly keys: string[];
}
/**
* Convert a {@link Params} instance to a {@link ParamMap}.
*
* @stable
*/
export declare function convertToParamMap(params: Params): ParamMap;
export declare function navigationCancelingError(message: string): Error;
export declare function isNavigationCancelingError(error: Error): any;
export declare function defaultUrlMatcher(segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult | null;

View File

@ -0,0 +1,41 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { UrlTree } from './url_tree';
/**
* @whatItDoes Provides a way to migrate AngularJS applications to Angular.
*
* @experimental
*/
export declare abstract class UrlHandlingStrategy {
/**
* Tells the router if this URL should be processed.
*
* When it returns true, the router will execute the regular navigation.
* When it returns false, the router will set the router state to an empty state.
* As a result, all the active components will be destroyed.
*
*/
abstract shouldProcessUrl(url: UrlTree): boolean;
/**
* Extracts the part of the URL that should be handled by the router.
* The rest of the URL will remain untouched.
*/
abstract extract(url: UrlTree): UrlTree;
/**
* Merges the URL fragment with the rest of the URL.
*/
abstract merge(newUrlPart: UrlTree, rawUrl: UrlTree): UrlTree;
}
/**
* @experimental
*/
export declare class DefaultUrlHandlingStrategy implements UrlHandlingStrategy {
shouldProcessUrl(url: UrlTree): boolean;
extract(url: UrlTree): UrlTree;
merge(newUrlPart: UrlTree, wholeUrl: UrlTree): UrlTree;
}

View File

@ -0,0 +1,183 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ParamMap } from './shared';
export declare function createEmptyUrlTree(): UrlTree;
export declare function containsTree(container: UrlTree, containee: UrlTree, exact: boolean): boolean;
/**
* @whatItDoes Represents the parsed URL.
*
* @howToUse
*
* ```
* @Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const tree: UrlTree =
* router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
* const f = tree.fragment; // return 'fragment'
* const q = tree.queryParams; // returns {debug: 'true'}
* const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
* const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
* g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
* g.children['support'].segments; // return 1 segment 'help'
* }
* }
* ```
*
* @description
*
* Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
* serialized tree.
* UrlTree is a data structure that provides a lot of affordances in dealing with URLs
*
* @stable
*/
export declare class UrlTree {
/** The root segment group of the URL tree */
root: UrlSegmentGroup;
/** The query params of the URL */
queryParams: {
[key: string]: string;
};
/** The fragment of the URL */
fragment: string | null;
readonly queryParamMap: ParamMap;
/** @docsNotRequired */
toString(): string;
}
/**
* @whatItDoes Represents the parsed URL segment group.
*
* See {@link UrlTree} for more information.
*
* @stable
*/
export declare class UrlSegmentGroup {
/** The URL segments of this group. See {@link UrlSegment} for more information */
segments: UrlSegment[];
/** The list of children of this group */
children: {
[key: string]: UrlSegmentGroup;
};
/** The parent node in the url tree */
parent: UrlSegmentGroup | null;
constructor(
/** The URL segments of this group. See {@link UrlSegment} for more information */
segments: UrlSegment[],
/** The list of children of this group */
children: {
[key: string]: UrlSegmentGroup;
});
/** Whether the segment has child segments */
hasChildren(): boolean;
/** Number of child segments */
readonly numberOfChildren: number;
/** @docsNotRequired */
toString(): string;
}
/**
* @whatItDoes Represents a single URL segment.
*
* @howToUse
*
* ```
* @Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const tree: UrlTree = router.parseUrl('/team;id=33');
* const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
* const s: UrlSegment[] = g.segments;
* s[0].path; // returns 'team'
* s[0].parameters; // returns {id: 33}
* }
* }
* ```
*
* @description
*
* A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
* parameters associated with the segment.
*
* @stable
*/
export declare class UrlSegment {
/** The path part of a URL segment */
path: string;
/** The matrix parameters associated with a segment */
parameters: {
[name: string]: string;
};
constructor(
/** The path part of a URL segment */
path: string,
/** The matrix parameters associated with a segment */
parameters: {
[name: string]: string;
});
readonly parameterMap: ParamMap;
/** @docsNotRequired */
toString(): string;
}
export declare function equalSegments(as: UrlSegment[], bs: UrlSegment[]): boolean;
export declare function equalPath(as: UrlSegment[], bs: UrlSegment[]): boolean;
export declare function mapChildrenIntoArray<T>(segment: UrlSegmentGroup, fn: (v: UrlSegmentGroup, k: string) => T[]): T[];
/**
* @whatItDoes Serializes and deserializes a URL string into a URL tree.
*
* @description The url serialization strategy is customizable. You can
* make all URLs case insensitive by providing a custom UrlSerializer.
*
* See {@link DefaultUrlSerializer} for an example of a URL serializer.
*
* @stable
*/
export declare abstract class UrlSerializer {
/** Parse a url into a {@link UrlTree} */
abstract parse(url: string): UrlTree;
/** Converts a {@link UrlTree} into a url */
abstract serialize(tree: UrlTree): string;
}
/**
* @whatItDoes A default implementation of the {@link UrlSerializer}.
*
* @description
*
* Example URLs:
*
* ```
* /inbox/33(popup:compose)
* /inbox/33;open=true/messages/44
* ```
*
* DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
* colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
* specify route specific parameters.
*
* @stable
*/
export declare class DefaultUrlSerializer implements UrlSerializer {
/** Parses a url into a {@link UrlTree} */
parse(url: string): UrlTree;
/** Converts a {@link UrlTree} into a url */
serialize(tree: UrlTree): string;
}
export declare function serializePaths(segment: UrlSegmentGroup): string;
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
export declare function encode(s: string): string;
export declare function decode(s: string): string;
export declare function serializePath(path: UrlSegment): string;

View File

@ -0,0 +1,41 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { NgModuleFactory } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export declare function shallowEqualArrays(a: any[], b: any[]): boolean;
export declare function shallowEqual(a: {
[x: string]: any;
}, b: {
[x: string]: any;
}): boolean;
/**
* Flattens single-level nested arrays.
*/
export declare function flatten<T>(arr: T[][]): T[];
/**
* Return the last element of an array.
*/
export declare function last<T>(a: T[]): T | null;
/**
* Verifys all booleans in an array are `true`.
*/
export declare function and(bools: boolean[]): boolean;
export declare function forEach<K, V>(map: {
[key: string]: V;
}, callback: (v: V, k: string) => void): void;
export declare function waitForMap<A, B>(obj: {
[k: string]: A;
}, fn: (k: string, a: A) => Observable<B>): Observable<{
[k: string]: B;
}>;
/**
* ANDs Observables by merging all input observables, reducing to an Observable verifying all
* input Observables return `true`.
*/
export declare function andObservables(observables: Observable<Observable<any>>): Observable<boolean>;
export declare function wrapIntoObservable<T>(value: T | NgModuleFactory<T> | Promise<T> | Observable<T>): Observable<T>;

View File

@ -0,0 +1,22 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export declare class Tree<T> {
constructor(root: TreeNode<T>);
readonly root: T;
}
export declare class TreeNode<T> {
value: T;
children: TreeNode<T>[];
constructor(value: T, children: TreeNode<T>[]);
toString(): string;
}
export declare function nodeChildrenAsMap<T extends {
outlet: string;
}>(node: TreeNode<T> | null): {
[outlet: string]: TreeNode<T>;
};

View File

@ -0,0 +1,17 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
import { Version } from '@angular/core';
/**
* @stable
*/
export declare const VERSION: Version;