angular-cn/modules/@angular/router/src/router_state.ts

456 lines
13 KiB
TypeScript
Raw Normal View History

/**
* @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';
2016-06-08 14:13:41 -04:00
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import {Data, ResolveData, Route} from './config';
2016-06-08 14:13:41 -04:00
import {PRIMARY_OUTLET, Params} from './shared';
import {UrlSegment, UrlSegmentGroup, UrlTree, equalSegments} from './url_tree';
import {merge, shallowEqual, shallowEqualArrays} from './utils/collection';
2016-06-08 14:13:41 -04:00
import {Tree, TreeNode} from './utils/tree';
2016-05-23 19:14:23 -04:00
2016-05-24 16:41:37 -04:00
/**
2016-09-10 19:53:09 -04:00
* @whatItDoes Represents the state of the router.
2016-05-24 16:41:37 -04:00
*
2016-09-10 19:53:09 -04:00
* @howToUse
2016-05-24 16:41:37 -04:00
*
* ```
2016-09-10 19:53:09 -04:00
* @Component({templateUrl:'template.html'})
2016-05-24 16:41:37 -04:00
* class MyComponent {
* constructor(router: Router) {
2016-09-10 19:53:09 -04:00
* const state: RouterState = router.routerState;
* const root: ActivatedRoute = state.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
2016-05-24 16:41:37 -04:00
* }
* }
* ```
*
2016-09-10 19:53:09 -04:00
* @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.
*
2016-06-28 17:49:29 -04:00
* @stable
2016-05-24 16:41:37 -04:00
*/
2016-05-23 19:14:23 -04:00
export class RouterState extends Tree<ActivatedRoute> {
/**
* @internal
*/
2016-09-10 19:53:09 -04:00
constructor(
root: TreeNode<ActivatedRoute>,
/**
* The current snapshot of the router state.
*/
public snapshot: RouterStateSnapshot) {
2016-05-23 19:14:23 -04:00
super(root);
setRouterStateSnapshot<RouterState, ActivatedRoute>(this, root);
2016-05-23 19:14:23 -04:00
}
2016-06-09 17:33:09 -04:00
toString(): string { return this.snapshot.toString(); }
2016-05-23 19:14:23 -04:00
}
export function createEmptyState(urlTree: UrlTree, rootComponent: Type<any>): RouterState {
2016-06-14 17:55:59 -04:00
const snapshot = createEmptyStateSnapshot(urlTree, rootComponent);
const emptyUrl = new BehaviorSubject([new UrlSegment('', {})]);
2016-05-23 19:14:23 -04:00
const emptyParams = new BehaviorSubject({});
const emptyData = new BehaviorSubject({});
2016-05-23 19:14:23 -04:00
const emptyQueryParams = new BehaviorSubject({});
2016-06-08 14:13:41 -04:00
const fragment = new BehaviorSubject('');
const activated = new ActivatedRoute(
emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent,
snapshot.root);
2016-06-02 17:44:57 -04:00
activated.snapshot = snapshot.root;
return new RouterState(new TreeNode<ActivatedRoute>(activated, []), snapshot);
2016-05-23 19:14:23 -04:00
}
export function createEmptyStateSnapshot(
urlTree: UrlTree, rootComponent: Type<any>): RouterStateSnapshot {
2016-06-01 16:29:02 -04:00
const emptyParams = {};
const emptyData = {};
2016-06-01 16:29:02 -04:00
const emptyQueryParams = {};
2016-06-08 14:13:41 -04:00
const fragment = '';
const activated = new ActivatedRouteSnapshot(
[], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null,
urlTree.root, -1, {});
return new RouterStateSnapshot('', new TreeNode<ActivatedRouteSnapshot>(activated, []));
2016-06-01 16:29:02 -04:00
}
2016-05-24 16:41:37 -04:00
/**
2016-09-10 19:53:09 -04:00
* @whatItDoes Contains the information about a route associated with a component loaded in an
* outlet.
* ActivatedRoute can also be used to traverse the router state tree.
2016-05-24 16:41:37 -04:00
*
2016-09-10 19:53:09 -04:00
* @howToUse
2016-05-24 16:41:37 -04:00
*
* ```
2016-09-10 19:53:09 -04:00
* @Component({templateUrl:'./my-component.html'})
2016-05-24 16:41:37 -04:00
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: Observable<string> = route.params.map(p => p.id);
2016-09-10 19:53:09 -04:00
* const url: Observable<string> = route.url.map(s => s.join(''));
* const user = route.data.map(d => d.user); //includes `data` and `resolve`
2016-05-24 16:41:37 -04:00
* }
* }
* ```
*
2016-06-28 17:49:29 -04:00
* @stable
2016-05-24 16:41:37 -04:00
*/
2016-05-23 19:14:23 -04:00
export class ActivatedRoute {
2016-06-02 17:44:57 -04:00
/** @internal */
_futureSnapshot: ActivatedRouteSnapshot;
2016-09-10 19:53:09 -04:00
/**
* The current snapshot of this route.
*/
2016-06-02 17:44:57 -04:00
snapshot: ActivatedRouteSnapshot;
/** @internal */
_routerState: RouterState;
/**
* @internal
*/
2016-06-08 14:13:41 -04:00
constructor(
2016-09-10 19:53:09 -04:00
/**
* The URL segments matched by this route. The observable will emit a new value when
* the array of segments changes.
*/
public url: Observable<UrlSegment[]>,
/**
* The matrix parameters scoped to this route. The observable will emit a new value when
* the set of the parameters changes.
*/
public params: Observable<Params>,
/**
* The query parameters shared by all the routes. The observable will emit a new value when
* the set of the parameters changes.
*/
public queryParams: Observable<Params>,
/**
* The URL fragment shared by all the routes. The observable will emit a new value when
* the URL fragment changes.
*/
public fragment: Observable<string>,
/**
* The static and resolved data of this route. The observable will emit a new value when
* any of the resolvers returns a new object.
*/
public data: Observable<Data>,
/**
* The outlet name of the route. It's a constant.
*/
public outlet: string,
/**
* The component of the route. It's a constant.
*/
public component: Type<any>|string, // TODO: vsavkin: remove |string
2016-06-08 14:13:41 -04:00
futureSnapshot: ActivatedRouteSnapshot) {
2016-06-02 17:44:57 -04:00
this._futureSnapshot = futureSnapshot;
}
2016-09-10 19:53:09 -04:00
/**
* The configuration used to match this route.
*/
get routeConfig(): Route { return this._futureSnapshot.routeConfig; }
2016-09-10 19:53:09 -04:00
/**
* The root of the router state.
*/
get root(): ActivatedRoute { return this._routerState.root; }
2016-09-10 19:53:09 -04:00
/**
* The parent of this route in the router state tree.
*/
get parent(): ActivatedRoute { return this._routerState.parent(this); }
2016-09-10 19:53:09 -04:00
/**
* The first child of this route in the router state tree.
*/
get firstChild(): ActivatedRoute { return this._routerState.firstChild(this); }
2016-09-10 19:53:09 -04:00
/**
* The children of this route in the router state tree.
*/
get children(): ActivatedRoute[] { return this._routerState.children(this); }
2016-09-10 19:53:09 -04:00
/**
* The path from the root of the router state tree to this route.
*/
get pathFromRoot(): ActivatedRoute[] { return this._routerState.pathFromRoot(this); }
2016-09-10 19:53:09 -04:00
/**
* @docsNotRequired
*/
toString(): string {
return this.snapshot ? this.snapshot.toString() : `Future(${this._futureSnapshot})`;
}
2016-06-01 16:29:02 -04:00
}
2016-06-28 17:49:29 -04:00
/**
* @internal
*/
export type Inherited = {
params: Params; data: Data; resolve: Data;
}
/**
* @internal
*/
export function
inheritedParamsDataResolve(route: ActivatedRouteSnapshot):
Inherited {
const pathToRoot = route.pathFromRoot;
let inhertingStartingFrom = pathToRoot.length - 1;
while (inhertingStartingFrom >= 1) {
const current = pathToRoot[inhertingStartingFrom];
const parent = pathToRoot[inhertingStartingFrom - 1];
// current route is an empty path => inherits its parent's params and data
if (current.routeConfig && current.routeConfig.path === '') {
inhertingStartingFrom--;
// parent is componentless => current route should inherit its params and data
} else if (!parent.component) {
inhertingStartingFrom--;
} else {
break;
}
}
return pathToRoot.slice(inhertingStartingFrom).reduce((res, curr) => {
const params = merge(res.params, curr.params);
const data = merge(res.data, curr.data);
const resolve = merge(res.resolve, curr._resolvedData);
return {params, data, resolve};
}, <any>{params: {}, data: {}, resolve: {}});
}
/**
2016-09-10 19:53:09 -04:00
* @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.
*
2016-09-10 19:53:09 -04:00
* @howToUse
*
* ```
2016-09-10 19:53:09 -04:00
* @Component({templateUrl:'./my-component.html'})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: string = route.snapshot.params.id;
2016-09-10 19:53:09 -04:00
* const url: string = route.snapshot.url.join('');
* const user = route.snapshot.data.user;
* }
* }
* ```
*
2016-06-28 17:49:29 -04:00
* @stable
*/
export class ActivatedRouteSnapshot {
2016-06-01 16:29:02 -04:00
/** @internal **/
_routeConfig: Route;
2016-06-01 16:29:02 -04:00
2016-06-02 14:30:38 -04:00
/** @internal **/
_urlSegment: UrlSegmentGroup;
2016-06-14 17:55:59 -04:00
/** @internal */
2016-06-14 17:55:59 -04:00
_lastPathIndex: number;
2016-06-02 14:30:38 -04:00
/** @internal */
_resolve: ResolveData;
/** @internal */
_resolvedData: Data;
/** @internal */
_routerState: RouterStateSnapshot;
/**
* @internal
*/
2016-06-08 14:13:41 -04:00
constructor(
2016-09-10 19:53:09 -04:00
/**
* The URL segments matched by this route.
*/
public url: UrlSegment[],
/**
* The matrix parameters scoped to this route.
*/
public params: Params,
/**
* The query parameters shared by all the routes.
*/
public queryParams: Params,
/**
* The URL fragment shared by all the routes.
*/
public fragment: string,
/**
* The static and resolved data of this route.
*/
public data: Data,
/**
* The outlet name of the route.
*/
public outlet: string,
/**
* The component of the route.
*/
public component: Type<any>|string, routeConfig: Route, urlSegment: UrlSegmentGroup,
lastPathIndex: number, resolve: ResolveData) {
2016-06-01 16:29:02 -04:00
this._routeConfig = routeConfig;
2016-06-14 17:55:59 -04:00
this._urlSegment = urlSegment;
this._lastPathIndex = lastPathIndex;
this._resolve = resolve;
2016-06-01 16:29:02 -04:00
}
2016-09-10 19:53:09 -04:00
/**
* The configuration used to match this route.
*/
get routeConfig(): Route { return this._routeConfig; }
2016-09-10 19:53:09 -04:00
/**
* The root of the router state.
*/
get root(): ActivatedRouteSnapshot { return this._routerState.root; }
2016-09-10 19:53:09 -04:00
/**
* The parent of this route in the router state tree.
*/
get parent(): ActivatedRouteSnapshot { return this._routerState.parent(this); }
2016-09-10 19:53:09 -04:00
/**
* The first child of this route in the router state tree.
*/
get firstChild(): ActivatedRouteSnapshot { return this._routerState.firstChild(this); }
2016-09-10 19:53:09 -04:00
/**
* The children of this route in the router state tree.
*/
get children(): ActivatedRouteSnapshot[] { return this._routerState.children(this); }
2016-09-10 19:53:09 -04:00
/**
* The path from the root of the router state tree to this route.
*/
get pathFromRoot(): ActivatedRouteSnapshot[] { return this._routerState.pathFromRoot(this); }
2016-09-10 19:53:09 -04:00
/**
* @docsNotRequired
*/
toString(): string {
2016-06-14 17:55:59 -04:00
const url = this.url.map(s => s.toString()).join('/');
const matched = this._routeConfig ? this._routeConfig.path : '';
return `Route(url:'${url}', path:'${matched}')`;
}
2016-06-01 16:29:02 -04:00
}
/**
2016-09-10 19:53:09 -04:00
* @whatItDoes Represents the state of the router at a moment in time.
*
2016-09-10 19:53:09 -04:00
* @howToUse
*
* ```
2016-09-10 19:53:09 -04:00
* @Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
2016-09-10 19:53:09 -04:00
* 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);
* //...
* }
* }
* ```
*
2016-09-10 19:53:09 -04:00
* @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.
*
2016-06-28 17:49:29 -04:00
* @stable
*/
export class RouterStateSnapshot extends Tree<ActivatedRouteSnapshot> {
/**
* @internal
*/
2016-09-10 19:53:09 -04:00
constructor(
/** The url from which this snapshot was created */
public url: string, root: TreeNode<ActivatedRouteSnapshot>) {
2016-06-01 16:29:02 -04:00
super(root);
setRouterStateSnapshot<RouterStateSnapshot, ActivatedRouteSnapshot>(this, root);
2016-06-01 16:29:02 -04:00
}
2016-06-09 17:33:09 -04:00
toString(): string { return serializeNode(this._root); }
2016-06-02 17:44:57 -04:00
}
function setRouterStateSnapshot<U, T extends{_routerState: U}>(state: U, node: TreeNode<T>): void {
node.value._routerState = state;
node.children.forEach(c => setRouterStateSnapshot(state, c));
}
function serializeNode(node: TreeNode<ActivatedRouteSnapshot>): string {
const c = node.children.length > 0 ? ` { ${node.children.map(serializeNode).join(", ")} } ` : '';
return `${node.value}${c}`;
}
2016-06-02 17:44:57 -04:00
/**
* 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 function advanceActivatedRoute(route: ActivatedRoute): void {
if (route.snapshot) {
if (!shallowEqual(route.snapshot.queryParams, route._futureSnapshot.queryParams)) {
(<any>route.queryParams).next(route._futureSnapshot.queryParams);
}
if (route.snapshot.fragment !== route._futureSnapshot.fragment) {
(<any>route.fragment).next(route._futureSnapshot.fragment);
}
if (!shallowEqual(route.snapshot.params, route._futureSnapshot.params)) {
(<any>route.params).next(route._futureSnapshot.params);
(<any>route.data).next(route._futureSnapshot.data);
}
if (!shallowEqualArrays(route.snapshot.url, route._futureSnapshot.url)) {
(<any>route.url).next(route._futureSnapshot.url);
}
2016-06-02 17:44:57 -04:00
route.snapshot = route._futureSnapshot;
} else {
route.snapshot = route._futureSnapshot;
// this is for resolved data
(<any>route.data).next(route._futureSnapshot.data);
2016-06-02 17:44:57 -04:00
}
}
export function equalParamsAndUrlSegments(
a: ActivatedRouteSnapshot, b: ActivatedRouteSnapshot): boolean {
return shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
}