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

517 lines
17 KiB
TypeScript
Raw Normal View History

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/mergeMap';
2016-06-03 17:07:01 -04:00
import 'rxjs/add/operator/concat';
import 'rxjs/add/operator/concatMap';
import 'rxjs/add/operator/every';
import 'rxjs/add/operator/mergeAll';
import 'rxjs/add/observable/from';
2016-06-08 14:13:41 -04:00
import {Location} from '@angular/common';
import {ComponentResolver, Injector, ReflectiveInjector, Type} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {Subscription} from 'rxjs/Subscription';
import {of } from 'rxjs/observable/of';
2016-06-08 19:14:26 -04:00
import {applyRedirects} from './apply_redirects';
2016-06-08 14:13:41 -04:00
import {RouterConfig} from './config';
import {createRouterState} from './create_router_state';
import {createUrlTree} from './create_url_tree';
import {RouterOutlet} from './directives/router_outlet';
import {recognize} from './recognize';
import {resolve} from './resolve';
import {RouterOutletMap} from './router_outlet_map';
import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, advanceActivatedRoute, createEmptyState} from './router_state';
import {PRIMARY_OUTLET, Params} from './shared';
import {UrlSerializer} from './url_serializer';
import {UrlTree, createEmptyUrlTree} from './url_tree';
import {forEach, shallowEqual} from './utils/collection';
2016-06-08 14:13:41 -04:00
import {TreeNode} from './utils/tree';
export interface NavigationExtras {
relativeTo?: ActivatedRoute;
queryParams?: Params;
fragment?: string;
}
2016-06-03 17:28:41 -04:00
/**
* An event triggered when a navigation starts
*/
2016-06-08 14:13:41 -04:00
export class NavigationStart {
constructor(public id: number, public url: UrlTree) {}
2016-06-09 17:32:03 -04:00
2016-06-09 17:33:09 -04:00
toString(): string { return `NavigationStart(id: ${this.id}, url: '${this.url}')`; }
2016-06-08 14:13:41 -04:00
}
2016-06-03 17:28:41 -04:00
/**
* An event triggered when a navigation ends successfully
*/
2016-06-08 14:13:41 -04:00
export class NavigationEnd {
constructor(public id: number, public url: UrlTree) {}
2016-06-09 17:32:03 -04:00
2016-06-09 17:33:09 -04:00
toString(): string { return `NavigationEnd(id: ${this.id}, url: '${this.url}')`; }
2016-06-08 14:13:41 -04:00
}
2016-06-03 17:28:41 -04:00
/**
* An event triggered when a navigation is canceled
*/
2016-06-08 14:13:41 -04:00
export class NavigationCancel {
constructor(public id: number, public url: UrlTree) {}
2016-06-09 17:32:03 -04:00
2016-06-09 17:33:09 -04:00
toString(): string { return `NavigationCancel(id: ${this.id}, url: '${this.url}')`; }
2016-06-08 14:13:41 -04:00
}
2016-06-03 17:28:41 -04:00
/**
* An event triggered when a navigation fails due to unexpected error
*/
2016-06-08 14:13:41 -04:00
export class NavigationError {
constructor(public id: number, public url: UrlTree, public error: any) {}
2016-06-09 17:32:03 -04:00
toString(): string {
return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`;
}
2016-06-08 14:13:41 -04:00
}
2016-06-03 17:28:41 -04:00
/**
* An event triggered when routes are recognized
*/
export class RoutesRecognized {
2016-06-09 17:33:09 -04:00
constructor(
public id: number, public url: UrlTree, public urlAfterRedirects: UrlTree,
public state: RouterStateSnapshot) {}
2016-06-09 17:32:03 -04:00
toString(): string {
return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
}
}
export type Event = NavigationStart | NavigationEnd | NavigationCancel | NavigationError;
2016-05-24 16:41:37 -04:00
/**
* The `Router` is responsible for mapping URLs to components.
*/
export class Router {
private currentUrlTree: UrlTree;
private currentRouterState: RouterState;
private locationSubscription: Subscription;
private routerEvents: Subject<Event>;
2016-06-03 17:07:01 -04:00
private navigationId: number = 0;
2016-05-24 16:41:37 -04:00
/**
* @internal
*/
2016-06-08 14:13:41 -04:00
constructor(
private rootComponentType: Type, private resolver: ComponentResolver,
private urlSerializer: UrlSerializer, private outletMap: RouterOutletMap,
2016-06-09 17:33:09 -04:00
private location: Location, private injector: g Injector, private config: RouterConfig) {
this.routerEvents = new Subject<Event>();
2016-06-07 12:50:35 -04:00
this.currentUrlTree = createEmptyUrlTree();
this.currentRouterState = createEmptyState(this.rootComponentType);
}
/**
* @internal
*/
2016-06-08 14:13:41 -04:00
initialNavigation(): void {
this.setUpLocationChangeListener();
this.navigateByUrl(this.location.path());
}
2016-05-24 16:41:37 -04:00
/**
* Returns the current route state.
*/
2016-06-08 14:13:41 -04:00
get routerState(): RouterState { return this.currentRouterState; }
/**
* Returns the current url tree.
*/
2016-06-08 14:13:41 -04:00
get urlTree(): UrlTree { return this.currentUrlTree; }
2016-05-24 16:41:37 -04:00
2016-06-03 17:28:41 -04:00
/**
* Returns an observable of route events
*/
2016-06-08 14:13:41 -04:00
get events(): Observable<Event> { return this.routerEvents; }
2016-05-24 16:41:37 -04:00
/**
* Navigate based on the provided url. This navigation is always absolute.
*
2016-06-03 17:28:41 -04:00
* Returns a promise that:
* - is resolved with 'true' when navigation succeeds
* - is resolved with 'false' when navigation fails
* - is rejected when an error happens
*
2016-05-24 16:41:37 -04:00
* ### Usage
*
* ```
* router.navigateByUrl("/team/33/user/11");
* ```
*/
2016-06-03 17:07:01 -04:00
navigateByUrl(url: string): Promise<boolean> {
const urlTree = this.urlSerializer.parse(url);
2016-06-03 17:07:01 -04:00
return this.scheduleNavigation(urlTree, false);
}
2016-05-24 16:41:37 -04:00
/**
* 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 }
2016-05-24 16:41:37 -04:00
* ] }
* ]);
* ```
*/
2016-06-08 14:13:41 -04:00
resetConfig(config: RouterConfig): void { this.config = config; }
2016-05-24 17:33:34 -04:00
/**
* @internal
*/
dispose(): void { this.locationSubscription.unsubscribe(); }
/**
* 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 fragments like this
* router.createUrlTree(['/team/33/user', userId]);
*
* // 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});
* ```
*/
2016-06-08 14:13:41 -04:00
createUrlTree(commands: any[], {relativeTo, queryParams, fragment}: NavigationExtras = {}):
UrlTree {
const a = relativeTo ? relativeTo : this.routerState.root;
return createUrlTree(a, this.currentUrlTree, commands, queryParams, fragment);
}
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
2016-06-03 17:28:41 -04:00
* Returns a promise that:
* - is resolved with 'true' when navigation succeeds
* - is resolved with 'false' when navigation fails
* - is rejected when an error happens
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'team', '11], {relativeTo: route});
* ```
*/
2016-06-03 17:07:01 -04:00
navigate(commands: any[], extras: NavigationExtras = {}): Promise<boolean> {
return this.scheduleNavigation(this.createUrlTree(commands, extras), false);
}
/**
* Serializes a {@link UrlTree} into a string.
*/
serializeUrl(url: UrlTree): string { return this.urlSerializer.serialize(url); }
/**
* Parse a string into a {@link UrlTree}.
*/
parseUrl(url: string): UrlTree { return this.urlSerializer.parse(url); }
2016-06-08 14:13:41 -04:00
private scheduleNavigation(url: UrlTree, pop: boolean): Promise<boolean> {
const id = ++this.navigationId;
this.routerEvents.next(new NavigationStart(id, url));
2016-06-03 17:07:01 -04:00
return Promise.resolve().then((_) => this.runNavigate(url, false, id));
}
private setUpLocationChangeListener(): void {
this.locationSubscription = <any>this.location.subscribe((change) => {
2016-06-03 17:07:01 -04:00
return this.scheduleNavigation(this.urlSerializer.parse(change['url']), change['pop']);
});
}
2016-06-08 14:13:41 -04:00
private runNavigate(url: UrlTree, pop: boolean, id: number): Promise<boolean> {
2016-06-03 17:07:01 -04:00
if (id !== this.navigationId) {
2016-06-09 14:02:57 -04:00
this.location.go(this.urlSerializer.serialize(this.currentUrlTree));
this.routerEvents.next(new NavigationCancel(id, url));
2016-06-03 17:07:01 -04:00
return Promise.resolve(false);
}
2016-06-01 16:34:48 -04:00
2016-06-03 17:07:01 -04:00
return new Promise((resolvePromise, rejectPromise) => {
2016-06-08 19:14:26 -04:00
let updatedUrl;
2016-06-03 17:07:01 -04:00
let state;
2016-06-08 19:14:26 -04:00
applyRedirects(url, this.config)
.mergeMap(u => {
updatedUrl = u;
return recognize(this.rootComponentType, this.config, updatedUrl);
})
2016-06-08 14:13:41 -04:00
.mergeMap((newRouterStateSnapshot) => {
2016-06-09 17:33:09 -04:00
this.routerEvents.next(
new RoutesRecognized(id, url, updatedUrl, newRouterStateSnapshot));
2016-06-08 14:13:41 -04:00
return resolve(this.resolver, newRouterStateSnapshot);
})
.map((routerStateSnapshot) => {
return createRouterState(routerStateSnapshot, this.currentRouterState);
})
.map((newState: RouterState) => {
state = newState;
})
.mergeMap(_ => {
return new GuardChecks(state.snapshot, this.currentRouterState.snapshot, this.injector)
.check(this.outletMap);
})
.forEach((shouldActivate) => {
if (!shouldActivate || id !== this.navigationId) {
2016-06-09 14:02:57 -04:00
this.location.go(this.urlSerializer.serialize(this.currentUrlTree));
2016-06-08 14:13:41 -04:00
this.routerEvents.next(new NavigationCancel(id, url));
return Promise.resolve(false);
}
new ActivateRoutes(state, this.currentRouterState).activate(this.outletMap);
this.currentUrlTree = url;
this.currentRouterState = state;
if (!pop) {
2016-06-08 19:14:26 -04:00
this.location.go(this.urlSerializer.serialize(updatedUrl));
2016-06-08 14:13:41 -04:00
}
})
.then(
() => {
this.routerEvents.next(new NavigationEnd(id, url));
resolvePromise(true);
},
e => {
this.routerEvents.next(new NavigationError(id, url, e));
rejectPromise(e);
});
});
}
}
2016-06-08 14:13:41 -04:00
class CanActivate {
constructor(public route: ActivatedRouteSnapshot) {}
}
class CanDeactivate {
constructor(public component: Object, public route: ActivatedRouteSnapshot) {}
}
2016-06-02 17:44:57 -04:00
class GuardChecks {
private checks = [];
2016-06-08 14:13:41 -04:00
constructor(
private future: RouterStateSnapshot, private curr: RouterStateSnapshot,
private injector: Injector) {}
check(parentOutletMap: RouterOutletMap): Observable<boolean> {
const futureRoot = this.future._root;
const currRoot = this.curr ? this.curr._root : null;
this.traverseChildRoutes(futureRoot, currRoot, parentOutletMap);
2016-06-08 14:13:41 -04:00
if (this.checks.length === 0) return of (true);
return Observable.from(this.checks)
.map(s => {
if (s instanceof CanActivate) {
return this.runCanActivate(s.route);
} else if (s instanceof CanDeactivate) {
return this.runCanDeactivate(s.component, s.route);
} else {
throw new Error('Cannot be reached');
}
})
.mergeAll()
.every(result => result === true);
}
2016-06-08 14:13:41 -04:00
private traverseChildRoutes(
futureNode: TreeNode<ActivatedRouteSnapshot>, currNode: TreeNode<ActivatedRouteSnapshot>|null,
outletMap: RouterOutletMap|null): void {
const prevChildren = nodeChildrenAsMap(currNode);
futureNode.children.forEach(c => {
this.traverseRoutes(c, prevChildren[c.value.outlet], outletMap);
delete prevChildren[c.value.outlet];
});
2016-06-02 17:44:57 -04:00
forEach(prevChildren, (v, k) => this.deactivateOutletAndItChildren(v, outletMap._outlets[k]));
}
2016-06-08 14:13:41 -04:00
traverseRoutes(
futureNode: TreeNode<ActivatedRouteSnapshot>, currNode: TreeNode<ActivatedRouteSnapshot>|null,
parentOutletMap: RouterOutletMap|null): void {
const future = futureNode.value;
const curr = currNode ? currNode.value : null;
2016-06-02 17:44:57 -04:00
const outlet = parentOutletMap ? parentOutletMap._outlets[futureNode.value.outlet] : null;
2016-06-02 17:44:57 -04:00
if (curr && future._routeConfig === curr._routeConfig) {
if (!shallowEqual(future.params, curr.params)) {
2016-06-02 17:44:57 -04:00
this.checks.push(new CanDeactivate(outlet.component, curr), new CanActivate(future));
}
2016-06-02 17:44:57 -04:00
this.traverseChildRoutes(futureNode, currNode, outlet ? outlet.outletMap : null);
} else {
2016-06-02 17:44:57 -04:00
this.deactivateOutletAndItChildren(curr, outlet);
this.checks.push(new CanActivate(future));
this.traverseChildRoutes(futureNode, null, outlet ? outlet.outletMap : null);
}
}
2016-06-02 17:44:57 -04:00
private deactivateOutletAndItChildren(route: ActivatedRouteSnapshot, outlet: RouterOutlet): void {
if (outlet && outlet.isActivated) {
2016-06-08 14:13:41 -04:00
forEach(
outlet.outletMap._outlets,
2016-06-09 14:02:57 -04:00
(v, k) => this.deactivateOutletAndItChildren(v.activatedRoute.snapshot, v));
2016-06-07 12:50:35 -04:00
this.checks.push(new CanDeactivate(outlet.component, route));
2016-06-02 17:44:57 -04:00
}
}
private runCanActivate(future: ActivatedRouteSnapshot): Observable<boolean> {
const canActivate = future._routeConfig ? future._routeConfig.canActivate : null;
2016-06-08 14:13:41 -04:00
if (!canActivate || canActivate.length === 0) return of (true);
return Observable.from(canActivate)
.map(c => {
const guard = this.injector.get(c);
if (guard.canActivate) {
return wrapIntoObservable(guard.canActivate(future, this.future));
} else {
return wrapIntoObservable(guard(future, this.future));
}
})
.mergeAll()
.every(result => result === true);
}
2016-06-02 17:44:57 -04:00
private runCanDeactivate(component: Object, curr: ActivatedRouteSnapshot): Observable<boolean> {
const canDeactivate = curr._routeConfig ? curr._routeConfig.canDeactivate : null;
2016-06-08 14:13:41 -04:00
if (!canDeactivate || canDeactivate.length === 0) return of (true);
return Observable.from(canDeactivate)
.map(c => {
const guard = this.injector.get(c);
if (guard.canDeactivate) {
return wrapIntoObservable(guard.canDeactivate(component, curr, this.curr));
} else {
return wrapIntoObservable(guard(component, curr, this.curr));
}
})
.mergeAll()
.every(result => result === true);
2016-06-02 17:44:57 -04:00
}
}
function wrapIntoObservable<T>(value: T | Observable<T>): Observable<T> {
if (value instanceof Observable) {
return value;
} else {
2016-06-08 14:13:41 -04:00
return of (value);
}
}
class ActivateRoutes {
constructor(private futureState: RouterState, private currState: RouterState) {}
2016-06-08 14:13:41 -04:00
activate(parentOutletMap: RouterOutletMap): void {
2016-06-01 16:34:48 -04:00
const futureRoot = this.futureState._root;
const currRoot = this.currState ? this.currState._root : null;
pushQueryParamsAndFragment(this.futureState);
this.activateChildRoutes(futureRoot, currRoot, parentOutletMap);
}
2016-06-08 14:13:41 -04:00
private activateChildRoutes(
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>|null,
outletMap: RouterOutletMap): void {
const prevChildren = nodeChildrenAsMap(currNode);
futureNode.children.forEach(c => {
this.activateRoutes(c, prevChildren[c.value.outlet], outletMap);
delete prevChildren[c.value.outlet];
});
forEach(prevChildren, (v, k) => this.deactivateOutletAndItChildren(outletMap._outlets[k]));
}
2016-06-08 14:13:41 -04:00
activateRoutes(
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>|null,
parentOutletMap: RouterOutletMap): void {
const future = futureNode.value;
const curr = currNode ? currNode.value : null;
const outlet = getOutlet(parentOutletMap, futureNode.value);
if (future === curr) {
2016-06-02 17:44:57 -04:00
advanceActivatedRoute(future);
this.activateChildRoutes(futureNode, currNode, outlet.outletMap);
} else {
this.deactivateOutletAndItChildren(outlet);
const outletMap = new RouterOutletMap();
this.activateNewRoutes(outletMap, future, outlet);
this.activateChildRoutes(futureNode, null, outletMap);
}
}
2016-06-08 14:13:41 -04:00
private activateNewRoutes(
outletMap: RouterOutletMap, future: ActivatedRoute, outlet: RouterOutlet): void {
const resolved = ReflectiveInjector.resolve([
{provide: ActivatedRoute, useValue: future},
{provide: RouterOutletMap, useValue: outletMap}
]);
2016-06-09 14:02:57 -04:00
outlet.activate(future._futureSnapshot._resolvedComponentFactory, future, resolved, outletMap);
2016-06-02 17:44:57 -04:00
advanceActivatedRoute(future);
}
private deactivateOutletAndItChildren(outlet: RouterOutlet): void {
if (outlet && outlet.isActivated) {
forEach(outlet.outletMap._outlets, (v, k) => this.deactivateOutletAndItChildren(v));
outlet.deactivate();
}
}
}
function pushQueryParamsAndFragment(state: RouterState): void {
if (!shallowEqual(state.snapshot.queryParams, (<any>state.queryParams).value)) {
(<any>state.queryParams).next(state.snapshot.queryParams);
}
if (state.snapshot.fragment !== (<any>state.fragment).value) {
(<any>state.fragment).next(state.snapshot.fragment);
}
2016-06-01 16:34:48 -04:00
}
2016-06-08 14:13:41 -04:00
function nodeChildrenAsMap(node: TreeNode<any>| null) {
return node ? node.children.reduce((m, c) => {
m[c.value.outlet] = c;
return m;
}, {}) : {};
}
function getOutlet(outletMap: RouterOutletMap, route: ActivatedRoute): RouterOutlet {
let outlet = outletMap._outlets[route.outlet];
if (!outlet) {
if (route.outlet === PRIMARY_OUTLET) {
throw new Error(`Cannot find primary outlet`);
} else {
throw new Error(`Cannot find the outlet ${route.outlet}`);
}
}
return outlet;
}