fix(router): preserve resolve data

Closes #12306
This commit is contained in:
vsavkin 2016-10-25 14:33:18 -07:00
parent 7d2554baa1
commit 6ccbfd41dd
6 changed files with 119 additions and 115 deletions

View File

@ -12,7 +12,7 @@ import {Observer} from 'rxjs/Observer';
import {of } from 'rxjs/observable/of'; import {of } from 'rxjs/observable/of';
import {Data, ResolveData, Route, Routes} from './config'; import {Data, ResolveData, Route, Routes} from './config';
import {ActivatedRouteSnapshot, InheritedResolve, RouterStateSnapshot} from './router_state'; import {ActivatedRouteSnapshot, RouterStateSnapshot, inheritedParamsDataResolve} from './router_state';
import {PRIMARY_OUTLET, Params} from './shared'; import {PRIMARY_OUTLET, Params} from './shared';
import {UrlSegment, UrlSegmentGroup, UrlTree, mapChildrenIntoArray} from './url_tree'; import {UrlSegment, UrlSegmentGroup, UrlTree, mapChildrenIntoArray} from './url_tree';
import {last, merge} from './utils/collection'; import {last, merge} from './utils/collection';
@ -20,22 +20,6 @@ import {TreeNode} from './utils/tree';
class NoMatch {} class NoMatch {}
class InheritedFromParent {
constructor(
public parent: InheritedFromParent, public snapshot: ActivatedRouteSnapshot,
public params: Params, public data: Data, public resolve: InheritedResolve) {}
get allParams(): Params {
return this.parent ? merge(this.parent.allParams, this.params) : this.params;
}
get allData(): Data { return this.parent ? merge(this.parent.allData, this.data) : this.data; }
static empty(snapshot: ActivatedRouteSnapshot): InheritedFromParent {
return new InheritedFromParent(null, snapshot, {}, {}, new InheritedResolve(null, {}));
}
}
export function recognize( export function recognize(
rootComponentType: Type<any>, config: Routes, urlTree: UrlTree, rootComponentType: Type<any>, config: Routes, urlTree: UrlTree,
url: string): Observable<RouterStateSnapshot> { url: string): Observable<RouterStateSnapshot> {
@ -51,17 +35,16 @@ class Recognizer {
try { try {
const rootSegmentGroup = split(this.urlTree.root, [], [], this.config).segmentGroup; const rootSegmentGroup = split(this.urlTree.root, [], [], this.config).segmentGroup;
const children = this.processSegmentGroup( const children = this.processSegmentGroup(this.config, rootSegmentGroup, PRIMARY_OUTLET);
this.config, rootSegmentGroup, InheritedFromParent.empty(null), PRIMARY_OUTLET);
const root = new ActivatedRouteSnapshot( const root = new ActivatedRouteSnapshot(
[], Object.freeze({}), Object.freeze(this.urlTree.queryParams), this.urlTree.fragment, {}, [], Object.freeze({}), Object.freeze(this.urlTree.queryParams), this.urlTree.fragment, {},
PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, {});
InheritedResolve.empty);
const rootNode = new TreeNode<ActivatedRouteSnapshot>(root, children); const rootNode = new TreeNode<ActivatedRouteSnapshot>(root, children);
const routeState = new RouterStateSnapshot(this.url, rootNode);
return of (new RouterStateSnapshot(this.url, rootNode)); this.inheriteParamsAndData(routeState._root);
return of (routeState);
} catch (e) { } catch (e) {
return new Observable<RouterStateSnapshot>( return new Observable<RouterStateSnapshot>(
@ -69,22 +52,29 @@ class Recognizer {
} }
} }
inheriteParamsAndData(routeNode: TreeNode<ActivatedRouteSnapshot>): void {
const route = routeNode.value;
processSegmentGroup( const i = inheritedParamsDataResolve(route);
config: Route[], segmentGroup: UrlSegmentGroup, inherited: InheritedFromParent, route.params = Object.freeze(i.params);
outlet: string): TreeNode<ActivatedRouteSnapshot>[] { route.data = Object.freeze(i.data);
routeNode.children.forEach(n => this.inheriteParamsAndData(n));
}
processSegmentGroup(config: Route[], segmentGroup: UrlSegmentGroup, outlet: string):
TreeNode<ActivatedRouteSnapshot>[] {
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return this.processChildren(config, segmentGroup, inherited); return this.processChildren(config, segmentGroup);
} else { } else {
return this.processSegment(config, segmentGroup, 0, segmentGroup.segments, inherited, outlet); return this.processSegment(config, segmentGroup, 0, segmentGroup.segments, outlet);
} }
} }
processChildren(config: Route[], segmentGroup: UrlSegmentGroup, inherited: InheritedFromParent): processChildren(config: Route[], segmentGroup: UrlSegmentGroup):
TreeNode<ActivatedRouteSnapshot>[] { TreeNode<ActivatedRouteSnapshot>[] {
const children = mapChildrenIntoArray( const children = mapChildrenIntoArray(
segmentGroup, segmentGroup, (child, childOutlet) => this.processSegmentGroup(config, child, childOutlet));
(child, childOutlet) => this.processSegmentGroup(config, child, inherited, childOutlet));
checkOutletNameUniqueness(children); checkOutletNameUniqueness(children);
sortActivatedRouteSnapshots(children); sortActivatedRouteSnapshots(children);
return children; return children;
@ -92,11 +82,10 @@ class Recognizer {
processSegment( processSegment(
config: Route[], segmentGroup: UrlSegmentGroup, pathIndex: number, segments: UrlSegment[], config: Route[], segmentGroup: UrlSegmentGroup, pathIndex: number, segments: UrlSegment[],
inherited: InheritedFromParent, outlet: string): TreeNode<ActivatedRouteSnapshot>[] { outlet: string): TreeNode<ActivatedRouteSnapshot>[] {
for (let r of config) { for (let r of config) {
try { try {
return this.processSegmentAgainstRoute( return this.processSegmentAgainstRoute(r, segmentGroup, pathIndex, segments, outlet);
r, segmentGroup, pathIndex, segments, inherited, outlet);
} catch (e) { } catch (e) {
if (!(e instanceof NoMatch)) throw e; if (!(e instanceof NoMatch)) throw e;
} }
@ -106,26 +95,21 @@ class Recognizer {
processSegmentAgainstRoute( processSegmentAgainstRoute(
route: Route, rawSegment: UrlSegmentGroup, pathIndex: number, segments: UrlSegment[], route: Route, rawSegment: UrlSegmentGroup, pathIndex: number, segments: UrlSegment[],
inherited: InheritedFromParent, outlet: string): TreeNode<ActivatedRouteSnapshot>[] { outlet: string): TreeNode<ActivatedRouteSnapshot>[] {
if (route.redirectTo) throw new NoMatch(); if (route.redirectTo) throw new NoMatch();
if ((route.outlet ? route.outlet : PRIMARY_OUTLET) !== outlet) throw new NoMatch(); if ((route.outlet ? route.outlet : PRIMARY_OUTLET) !== outlet) throw new NoMatch();
const newInheritedResolve = new InheritedResolve(inherited.resolve, getResolve(route));
if (route.path === '**') { if (route.path === '**') {
const params = segments.length > 0 ? last(segments).parameters : {}; const params = segments.length > 0 ? last(segments).parameters : {};
const snapshot = new ActivatedRouteSnapshot( const snapshot = new ActivatedRouteSnapshot(
segments, Object.freeze(merge(inherited.allParams, params)), segments, params, Object.freeze(this.urlTree.queryParams), this.urlTree.fragment,
Object.freeze(this.urlTree.queryParams), this.urlTree.fragment, getData(route), outlet, route.component, route, getSourceSegmentGroup(rawSegment),
merge(inherited.allData, getData(route)), outlet, route.component, route, getPathIndexShift(rawSegment) + segments.length, getResolve(route));
getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + segments.length,
newInheritedResolve);
return [new TreeNode<ActivatedRouteSnapshot>(snapshot, [])]; return [new TreeNode<ActivatedRouteSnapshot>(snapshot, [])];
} }
const {consumedSegments, parameters, lastChild} = const {consumedSegments, parameters, lastChild} = match(rawSegment, route, segments);
match(rawSegment, route, segments, inherited.snapshot);
const rawSlicedSegments = segments.slice(lastChild); const rawSlicedSegments = segments.slice(lastChild);
const childConfig = getChildConfig(route); const childConfig = getChildConfig(route);
@ -133,19 +117,14 @@ class Recognizer {
split(rawSegment, consumedSegments, rawSlicedSegments, childConfig); split(rawSegment, consumedSegments, rawSlicedSegments, childConfig);
const snapshot = new ActivatedRouteSnapshot( const snapshot = new ActivatedRouteSnapshot(
consumedSegments, Object.freeze(merge(inherited.allParams, parameters)), consumedSegments, parameters, Object.freeze(this.urlTree.queryParams),
Object.freeze(this.urlTree.queryParams), this.urlTree.fragment, this.urlTree.fragment, getData(route), outlet, route.component, route,
merge(inherited.allData, getData(route)), outlet, route.component, route,
getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length,
newInheritedResolve); getResolve(route));
const newInherited = route.component ?
InheritedFromParent.empty(snapshot) :
new InheritedFromParent(
inherited, snapshot, parameters, getData(route), newInheritedResolve);
if (slicedSegments.length === 0 && segmentGroup.hasChildren()) { if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
const children = this.processChildren(childConfig, segmentGroup, newInherited); const children = this.processChildren(childConfig, segmentGroup);
return [new TreeNode<ActivatedRouteSnapshot>(snapshot, children)]; return [new TreeNode<ActivatedRouteSnapshot>(snapshot, children)];
} else if (childConfig.length === 0 && slicedSegments.length === 0) { } else if (childConfig.length === 0 && slicedSegments.length === 0) {
@ -153,8 +132,7 @@ class Recognizer {
} else { } else {
const children = this.processSegment( const children = this.processSegment(
childConfig, segmentGroup, pathIndex + lastChild, slicedSegments, newInherited, childConfig, segmentGroup, pathIndex + lastChild, slicedSegments, PRIMARY_OUTLET);
PRIMARY_OUTLET);
return [new TreeNode<ActivatedRouteSnapshot>(snapshot, children)]; return [new TreeNode<ActivatedRouteSnapshot>(snapshot, children)];
} }
} }
@ -178,15 +156,12 @@ function getChildConfig(route: Route): Route[] {
} }
} }
function match( function match(segmentGroup: UrlSegmentGroup, route: Route, segments: UrlSegment[]) {
segmentGroup: UrlSegmentGroup, route: Route, segments: UrlSegment[],
parent: ActivatedRouteSnapshot) {
if (route.path === '') { if (route.path === '') {
if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) { if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
throw new NoMatch(); throw new NoMatch();
} else { } else {
const params = parent ? parent.params : {}; return {consumedSegments: [], lastChild: 0, parameters: {}};
return {consumedSegments: [], lastChild: 0, parameters: params};
} }
} }

View File

@ -21,14 +21,14 @@ import {mergeMap} from 'rxjs/operator/mergeMap';
import {reduce} from 'rxjs/operator/reduce'; import {reduce} from 'rxjs/operator/reduce';
import {applyRedirects} from './apply_redirects'; import {applyRedirects} from './apply_redirects';
import {ResolveData, Routes, validateConfig} from './config'; import {Data, ResolveData, Routes, validateConfig} from './config';
import {createRouterState} from './create_router_state'; import {createRouterState} from './create_router_state';
import {createUrlTree} from './create_url_tree'; import {createUrlTree} from './create_url_tree';
import {RouterOutlet} from './directives/router_outlet'; import {RouterOutlet} from './directives/router_outlet';
import {recognize} from './recognize'; import {recognize} from './recognize';
import {LoadedRouterConfig, RouterConfigLoader} from './router_config_loader'; import {LoadedRouterConfig, RouterConfigLoader} from './router_config_loader';
import {RouterOutletMap} from './router_outlet_map'; import {RouterOutletMap} from './router_outlet_map';
import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, advanceActivatedRoute, createEmptyState} from './router_state'; import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, advanceActivatedRoute, createEmptyState, inheritedParamsDataResolve} from './router_state';
import {NavigationCancelingError, PRIMARY_OUTLET, Params} from './shared'; import {NavigationCancelingError, PRIMARY_OUTLET, Params} from './shared';
import {DefaultUrlHandlingStrategy, UrlHandlingStrategy} from './url_handling_strategy'; import {DefaultUrlHandlingStrategy, UrlHandlingStrategy} from './url_handling_strategy';
import {UrlSerializer, UrlTree, containsTree, createEmptyUrlTree} from './url_tree'; import {UrlSerializer, UrlTree, containsTree, createEmptyUrlTree} from './url_tree';
@ -781,6 +781,7 @@ export class PreActivation {
} else { } else {
// we need to set the data // we need to set the data
future.data = curr.data; future.data = curr.data;
future._resolvedData = curr._resolvedData;
} }
// If we have a component, we need to go through an outlet. // If we have a component, we need to go through an outlet.
@ -881,9 +882,9 @@ export class PreActivation {
private runResolve(future: ActivatedRouteSnapshot): Observable<any> { private runResolve(future: ActivatedRouteSnapshot): Observable<any> {
const resolve = future._resolve; const resolve = future._resolve;
return map.call(this.resolveNode(resolve.current, future), (resolvedData: any): any => { return map.call(this.resolveNode(resolve, future), (resolvedData: any): any => {
resolve.resolvedData = resolvedData; future._resolvedData = resolvedData;
future.data = merge(future.data, resolve.flattenedResolvedData); future.data = merge(future.data, inheritedParamsDataResolve(future).resolve);
return null; return null;
}); });
} }

View File

@ -83,7 +83,7 @@ export function createEmptyStateSnapshot(
const fragment = ''; const fragment = '';
const activated = new ActivatedRouteSnapshot( const activated = new ActivatedRouteSnapshot(
[], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, [], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null,
urlTree.root, -1, InheritedResolve.empty); urlTree.root, -1, {});
return new RouterStateSnapshot('', new TreeNode<ActivatedRouteSnapshot>(activated, [])); return new RouterStateSnapshot('', new TreeNode<ActivatedRouteSnapshot>(activated, []));
} }
@ -207,25 +207,44 @@ export class ActivatedRoute {
/** /**
* @internal * @internal
*/ */
export class InheritedResolve { export type Inherited = {
/** params: Params; data: Data; resolve: Data;
* @internal
*/
resolvedData = {};
constructor(public parent: InheritedResolve, public current: ResolveData) {}
/**
* @internal
*/
get flattenedResolvedData(): Data {
return this.parent ? merge(this.parent.flattenedResolvedData, this.resolvedData) :
this.resolvedData;
}
static get empty(): InheritedResolve { return new InheritedResolve(null, {}); }
} }
/**
* @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: {}});
}
/** /**
* @whatItDoes Contains the information about a route associated with a component loaded in an * @whatItDoes Contains the information about a route associated with a component loaded in an
* outlet * outlet
@ -258,7 +277,10 @@ export class ActivatedRouteSnapshot {
_lastPathIndex: number; _lastPathIndex: number;
/** @internal */ /** @internal */
_resolve: InheritedResolve; _resolve: ResolveData;
/** @internal */
_resolvedData: Data;
/** @internal */ /** @internal */
_routerState: RouterStateSnapshot; _routerState: RouterStateSnapshot;
@ -301,7 +323,7 @@ export class ActivatedRouteSnapshot {
* The component of the route. * The component of the route.
*/ */
public component: Type<any>|string, routeConfig: Route, urlSegment: UrlSegmentGroup, public component: Type<any>|string, routeConfig: Route, urlSegment: UrlSegmentGroup,
lastPathIndex: number, resolve: InheritedResolve) { lastPathIndex: number, resolve: ResolveData) {
this._routeConfig = routeConfig; this._routeConfig = routeConfig;
this._urlSegment = urlSegment; this._urlSegment = urlSegment;
this._lastPathIndex = lastPathIndex; this._lastPathIndex = lastPathIndex;

View File

@ -695,6 +695,30 @@ describe('Integration', () => {
expect(e).toEqual('error'); expect(e).toEqual('error');
}))); })));
it('should preserve resolved data',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'parent',
resolve: {two: 'resolveTwo'},
children: [
{path: 'child1', component: CollectParamsCmp},
{path: 'child2', component: CollectParamsCmp}
]
}]);
let e: any = null;
router.navigateByUrl('/parent/child1');
advance(fixture);
router.navigateByUrl('/parent/child2');
advance(fixture);
const cmp = fixture.debugElement.children[1].componentInstance;
expect(cmp.route.snapshot.data).toEqual({two: 2});
})));
}); });
describe('router links', () => { describe('router links', () => {
@ -2102,9 +2126,9 @@ class CollectParamsCmp {
private params: any = []; private params: any = [];
private urls: any = []; private urls: any = [];
constructor(a: ActivatedRoute) { constructor(private route: ActivatedRoute) {
a.params.forEach(p => this.params.push(p)); route.params.forEach(p => this.params.push(p));
a.url.forEach(u => this.urls.push(u)); route.url.forEach(u => this.urls.push(u));
} }
recordedUrls(): string[] { recordedUrls(): string[] {

View File

@ -219,26 +219,7 @@ describe('recognize', () => {
[{path: 'a', resolve: {one: 'some-token'}, component: ComponentA}], 'a', [{path: 'a', resolve: {one: 'some-token'}, component: ComponentA}], 'a',
(s: RouterStateSnapshot) => { (s: RouterStateSnapshot) => {
const r: ActivatedRouteSnapshot = s.firstChild(s.root); const r: ActivatedRouteSnapshot = s.firstChild(s.root);
expect(r._resolve.current).toEqual({one: 'some-token'}); expect(r._resolve).toEqual({one: 'some-token'});
});
});
it('should reuse componentless route\'s resolve', () => {
checkRecognize(
[{
path: 'a',
resolve: {one: 'one'},
children: [
{path: '', resolve: {two: 'two'}, component: ComponentB},
{path: '', resolve: {three: 'three'}, component: ComponentC, outlet: 'aux'}
]
}],
'a', (s: RouterStateSnapshot) => {
const a: ActivatedRouteSnapshot = s.firstChild(s.root);
const c: ActivatedRouteSnapshot[] = s.children(<any>a);
expect(c[0]._resolve.parent).toBe(a._resolve);
expect(c[1]._resolve.parent).toBe(a._resolve);
}); });
}); });
}); });

View File

@ -8,9 +8,10 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {ResolveData} from '../src/config';
import {PreActivation, Router} from '../src/router'; import {PreActivation, Router} from '../src/router';
import {RouterOutletMap} from '../src/router_outlet_map'; import {RouterOutletMap} from '../src/router_outlet_map';
import {ActivatedRouteSnapshot, InheritedResolve, RouterStateSnapshot, createEmptyStateSnapshot} from '../src/router_state'; import {ActivatedRouteSnapshot, RouterStateSnapshot, createEmptyStateSnapshot} from '../src/router_state';
import {DefaultUrlSerializer} from '../src/url_tree'; import {DefaultUrlSerializer} from '../src/url_tree';
import {TreeNode} from '../src/utils/tree'; import {TreeNode} from '../src/utils/tree';
import {RouterTestingModule} from '../testing/router_testing_module'; import {RouterTestingModule} from '../testing/router_testing_module';
@ -39,7 +40,7 @@ describe('Router', () => {
beforeEach(() => { empty = createEmptyStateSnapshot(serializer.parse('/'), null); }); beforeEach(() => { empty = createEmptyStateSnapshot(serializer.parse('/'), null); });
it('should resolve data', () => { it('should resolve data', () => {
const r = new InheritedResolve(InheritedResolve.empty, {data: 'resolver'}); const r = {data: 'resolver'};
const n = createActivatedRouteSnapshot('a', {resolve: r}); const n = createActivatedRouteSnapshot('a', {resolve: r});
const s = new RouterStateSnapshot('url', new TreeNode(empty.root, [new TreeNode(n, [])])); const s = new RouterStateSnapshot('url', new TreeNode(empty.root, [new TreeNode(n, [])]));
@ -49,10 +50,10 @@ describe('Router', () => {
}); });
it('should wait for the parent resolve to complete', () => { it('should wait for the parent resolve to complete', () => {
const parentResolve = new InheritedResolve(InheritedResolve.empty, {data: 'resolver'}); const parentResolve = {data: 'resolver'};
const childResolve = new InheritedResolve(parentResolve, {}); const childResolve = {};
const parent = createActivatedRouteSnapshot('a', {resolve: parentResolve}); const parent = createActivatedRouteSnapshot(null, {resolve: parentResolve});
const child = createActivatedRouteSnapshot('b', {resolve: childResolve}); const child = createActivatedRouteSnapshot('b', {resolve: childResolve});
const s = new RouterStateSnapshot( const s = new RouterStateSnapshot(
@ -66,8 +67,8 @@ describe('Router', () => {
}); });
it('should copy over data when creating a snapshot', () => { it('should copy over data when creating a snapshot', () => {
const r1 = new InheritedResolve(InheritedResolve.empty, {data: 'resolver1'}); const r1 = {data: 'resolver1'};
const r2 = new InheritedResolve(InheritedResolve.empty, {data: 'resolver2'}); const r2 = {data: 'resolver2'};
const n1 = createActivatedRouteSnapshot('a', {resolve: r1}); const n1 = createActivatedRouteSnapshot('a', {resolve: r1});
const s1 = new RouterStateSnapshot('url', new TreeNode(empty.root, [new TreeNode(n1, [])])); const s1 = new RouterStateSnapshot('url', new TreeNode(empty.root, [new TreeNode(n1, [])]));