Skip to content

Commit b2e5580

Browse files
committed
refactor(router): cleanup to navigation stream for readability and documentation
* Pull out `activateRoutes` into new operator * Add `asyncTap` operator * Use `asyncTap` operator for router hooks and remove corresponding abstracted operators * Clean up formatting * Minor performance improvements
1 parent 8811a82 commit b2e5580

11 files changed

Lines changed: 524 additions & 457 deletions

‎packages/router/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export {RouterOutlet} from './directives/router_outlet';
1414
export {ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, Event, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouterEvent, RoutesRecognized, Scroll} from './events';
1515
export {CanActivate, CanActivateChild, CanDeactivate, CanLoad, Resolve} from './interfaces';
1616
export {DetachedRouteHandle, RouteReuseStrategy} from './route_reuse_strategy';
17-
export {NavigationExtras, NavigationTransition, Router} from './router';
17+
export {NavigationExtras, Router} from './router';
1818
export {ROUTES} from './router_config_loader';
1919
export {ExtraOptions, ROUTER_CONFIGURATION, ROUTER_INITIALIZER, RouterModule, provideRoutes} from './router_module';
2020
export {ChildrenOutletContexts, OutletContext} from './router_outlet_context';
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
/**
2+
* @license
3+
* Copyright Google Inc. All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {MonoTypeOperatorFunction} from 'rxjs';
10+
import {map} from 'rxjs/operators';
11+
12+
import {LoadedRouterConfig} from '../config';
13+
import {ActivationEnd, ChildActivationEnd, Event} from '../events';
14+
import {DetachedRouteHandleInternal, RouteReuseStrategy} from '../route_reuse_strategy';
15+
import {NavigationTransition} from '../router';
16+
import {ChildrenOutletContexts} from '../router_outlet_context';
17+
import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, advanceActivatedRoute} from '../router_state';
18+
import {forEach} from '../utils/collection';
19+
import {TreeNode, nodeChildrenAsMap} from '../utils/tree';
20+
21+
export const activateRoutes =
22+
(rootContexts: ChildrenOutletContexts, routeReuseStrategy: RouteReuseStrategy,
23+
forwardEvent: (evt: Event) => void): MonoTypeOperatorFunction<NavigationTransition> =>
24+
map(t => {
25+
new ActivateRoutes(
26+
routeReuseStrategy, t.targetRouterState !, t.currentRouterState, forwardEvent)
27+
.activate(rootContexts);
28+
return t;
29+
});
30+
31+
export class ActivateRoutes {
32+
constructor(
33+
private routeReuseStrategy: RouteReuseStrategy, private futureState: RouterState,
34+
private currState: RouterState, private forwardEvent: (evt: Event) => void) {}
35+
36+
activate(parentContexts: ChildrenOutletContexts): void {
37+
const futureRoot = this.futureState._root;
38+
const currRoot = this.currState ? this.currState._root : null;
39+
40+
this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);
41+
advanceActivatedRoute(this.futureState.root);
42+
this.activateChildRoutes(futureRoot, currRoot, parentContexts);
43+
}
44+
45+
// De-activate the child route that are not re-used for the future state
46+
private deactivateChildRoutes(
47+
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>|null,
48+
contexts: ChildrenOutletContexts): void {
49+
const children: {[outletName: string]: TreeNode<ActivatedRoute>} = nodeChildrenAsMap(currNode);
50+
51+
// Recurse on the routes active in the future state to de-activate deeper children
52+
futureNode.children.forEach(futureChild => {
53+
const childOutletName = futureChild.value.outlet;
54+
this.deactivateRoutes(futureChild, children[childOutletName], contexts);
55+
delete children[childOutletName];
56+
});
57+
58+
// De-activate the routes that will not be re-used
59+
forEach(children, (v: TreeNode<ActivatedRoute>, childName: string) => {
60+
this.deactivateRouteAndItsChildren(v, contexts);
61+
});
62+
}
63+
64+
private deactivateRoutes(
65+
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>,
66+
parentContext: ChildrenOutletContexts): void {
67+
const future = futureNode.value;
68+
const curr = currNode ? currNode.value : null;
69+
70+
if (future === curr) {
71+
// Reusing the node, check to see if the children need to be de-activated
72+
if (future.component) {
73+
// If we have a normal route, we need to go through an outlet.
74+
const context = parentContext.getContext(future.outlet);
75+
if (context) {
76+
this.deactivateChildRoutes(futureNode, currNode, context.children);
77+
}
78+
} else {
79+
// if we have a componentless route, we recurse but keep the same outlet map.
80+
this.deactivateChildRoutes(futureNode, currNode, parentContext);
81+
}
82+
} else {
83+
if (curr) {
84+
// Deactivate the current route which will not be re-used
85+
this.deactivateRouteAndItsChildren(currNode, parentContext);
86+
}
87+
}
88+
}
89+
90+
private deactivateRouteAndItsChildren(
91+
route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts): void {
92+
if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
93+
this.detachAndStoreRouteSubtree(route, parentContexts);
94+
} else {
95+
this.deactivateRouteAndOutlet(route, parentContexts);
96+
}
97+
}
98+
99+
private detachAndStoreRouteSubtree(
100+
route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts): void {
101+
const context = parentContexts.getContext(route.value.outlet);
102+
if (context && context.outlet) {
103+
const componentRef = context.outlet.detach();
104+
const contexts = context.children.onOutletDeactivated();
105+
this.routeReuseStrategy.store(route.value.snapshot, {componentRef, route, contexts});
106+
}
107+
}
108+
109+
private deactivateRouteAndOutlet(
110+
route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts): void {
111+
const context = parentContexts.getContext(route.value.outlet);
112+
113+
if (context) {
114+
const children: {[outletName: string]: any} = nodeChildrenAsMap(route);
115+
const contexts = route.value.component ? context.children : parentContexts;
116+
117+
forEach(children, (v: any, k: string) => this.deactivateRouteAndItsChildren(v, contexts));
118+
119+
if (context.outlet) {
120+
// Destroy the component
121+
context.outlet.deactivate();
122+
// Destroy the contexts for all the outlets that were in the component
123+
context.children.onOutletDeactivated();
124+
}
125+
}
126+
}
127+
128+
private activateChildRoutes(
129+
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>|null,
130+
contexts: ChildrenOutletContexts): void {
131+
const children: {[outlet: string]: any} = nodeChildrenAsMap(currNode);
132+
futureNode.children.forEach(c => {
133+
this.activateRoutes(c, children[c.value.outlet], contexts);
134+
this.forwardEvent(new ActivationEnd(c.value.snapshot));
135+
});
136+
if (futureNode.children.length) {
137+
this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot));
138+
}
139+
}
140+
141+
private activateRoutes(
142+
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>,
143+
parentContexts: ChildrenOutletContexts): void {
144+
const future = futureNode.value;
145+
const curr = currNode ? currNode.value : null;
146+
147+
advanceActivatedRoute(future);
148+
149+
// reusing the node
150+
if (future === curr) {
151+
if (future.component) {
152+
// If we have a normal route, we need to go through an outlet.
153+
const context = parentContexts.getOrCreateContext(future.outlet);
154+
this.activateChildRoutes(futureNode, currNode, context.children);
155+
} else {
156+
// if we have a componentless route, we recurse but keep the same outlet map.
157+
this.activateChildRoutes(futureNode, currNode, parentContexts);
158+
}
159+
} else {
160+
if (future.component) {
161+
// if we have a normal route, we need to place the component into the outlet and recurse.
162+
const context = parentContexts.getOrCreateContext(future.outlet);
163+
164+
if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
165+
const stored =
166+
(<DetachedRouteHandleInternal>this.routeReuseStrategy.retrieve(future.snapshot));
167+
this.routeReuseStrategy.store(future.snapshot, null);
168+
context.children.onOutletReAttached(stored.contexts);
169+
context.attachRef = stored.componentRef;
170+
context.route = stored.route.value;
171+
if (context.outlet) {
172+
// Attach right away when the outlet has already been instantiated
173+
// Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated
174+
context.outlet.attach(stored.componentRef, stored.route.value);
175+
}
176+
advanceActivatedRouteNodeAndItsChildren(stored.route);
177+
} else {
178+
const config = parentLoadedConfig(future.snapshot);
179+
const cmpFactoryResolver = config ? config.module.componentFactoryResolver : null;
180+
181+
context.attachRef = null;
182+
context.route = future;
183+
context.resolver = cmpFactoryResolver;
184+
if (context.outlet) {
185+
// Activate the outlet when it has already been instantiated
186+
// Otherwise it will get activated from its `ngOnInit` when instantiated
187+
context.outlet.activateWith(future, cmpFactoryResolver);
188+
}
189+
190+
this.activateChildRoutes(futureNode, null, context.children);
191+
}
192+
} else {
193+
// if we have a componentless route, we recurse but keep the same outlet map.
194+
this.activateChildRoutes(futureNode, null, parentContexts);
195+
}
196+
}
197+
}
198+
}
199+
200+
function advanceActivatedRouteNodeAndItsChildren(node: TreeNode<ActivatedRoute>): void {
201+
advanceActivatedRoute(node.value);
202+
node.children.forEach(advanceActivatedRouteNodeAndItsChildren);
203+
}
204+
205+
function parentLoadedConfig(snapshot: ActivatedRouteSnapshot): LoadedRouterConfig|null {
206+
for (let s = snapshot.parent; s; s = s.parent) {
207+
const route = s.routeConfig;
208+
if (route && route._loadedConfig) return route._loadedConfig;
209+
if (route && route.component) return null;
210+
}
211+
212+
return null;
213+
}

‎packages/router/src/operators/after_preactivation.ts‎

Lines changed: 0 additions & 25 deletions
This file was deleted.

‎packages/router/src/operators/apply_redirects.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import {Injector} from '@angular/core';
1010
import {MonoTypeOperatorFunction, Observable} from 'rxjs';
11-
import {flatMap, map} from 'rxjs/operators';
11+
import {map, switchMap} from 'rxjs/operators';
1212

1313
import {applyRedirects as applyRedirectsFn} from '../apply_redirects';
1414
import {Routes} from '../config';
@@ -20,8 +20,8 @@ export function applyRedirects(
2020
moduleInjector: Injector, configLoader: RouterConfigLoader, urlSerializer: UrlSerializer,
2121
config: Routes): MonoTypeOperatorFunction<NavigationTransition> {
2222
return function(source: Observable<NavigationTransition>) {
23-
return source.pipe(flatMap(
23+
return source.pipe(switchMap(
2424
t => applyRedirectsFn(moduleInjector, configLoader, urlSerializer, t.extractedUrl, config)
25-
.pipe(map(url => ({...t, urlAfterRedirects: url})))));
25+
.pipe(map(urlAfterRedirects => ({...t, urlAfterRedirects})))));
2626
};
2727
}

‎packages/router/src/operators/before_preactivation.ts‎

Lines changed: 0 additions & 25 deletions
This file was deleted.

‎packages/router/src/operators/check_guards.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export function checkGuards(): MonoTypeOperatorFunction<NavigationTransition> {
1616

1717
return source.pipe(mergeMap(t => {
1818
if (!t.preActivation) {
19-
throw 'Initialized PreActivation required to check guards';
19+
throw new Error('PreActivation required to check guards');
2020
}
2121
return t.preActivation.checkGuards().pipe(map(guardsResult => ({...t, guardsResult})));
2222
}));

‎packages/router/src/operators/recognize.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ export function recognize(
2222
return function(source: Observable<NavigationTransition>) {
2323
return source.pipe(mergeMap(
2424
t => recognizeFn(
25-
rootComponentType, config, t.urlAfterRedirects, serializer(t.extractedUrl),
25+
rootComponentType, config, t.urlAfterRedirects, serializer(t.urlAfterRedirects),
2626
paramsInheritanceStrategy)
2727
.pipe(map(targetSnapshot => ({...t, targetSnapshot})))));
2828
};

‎packages/router/src/operators/resolve_data.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,19 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import {MonoTypeOperatorFunction, Observable, OperatorFunction, from, of } from 'rxjs';
10-
import {map, mergeMap} from 'rxjs/operators';
9+
import {MonoTypeOperatorFunction, Observable} from 'rxjs';
1110

1211
import {NavigationTransition} from '../router';
12+
import {switchTap} from './switch_tap';
1313

1414
export function resolveData(paramsInheritanceStrategy: 'emptyOnly' | 'always'):
1515
MonoTypeOperatorFunction<NavigationTransition> {
1616
return function(source: Observable<NavigationTransition>) {
17-
return source.pipe(mergeMap(t => {
17+
return source.pipe(switchTap(t => {
1818
if (!t.preActivation) {
19-
throw 'Initialized PreActivation required to check guards';
19+
throw new Error('PreActivation required to resolve data');
2020
}
21-
return t.preActivation.resolveData(paramsInheritanceStrategy).pipe(map(_ => t));
21+
return t.preActivation.resolveData(paramsInheritanceStrategy);
2222
}));
2323
};
2424
}

‎packages/router/src/operators/setup_preactivation.ts‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,12 @@ import {PreActivation} from '../pre_activation';
1515
import {ChildrenOutletContexts} from '../router_outlet_context';
1616
import {RouterStateSnapshot} from '../router_state';
1717

18-
export function setupPreactivation(
19-
rootContexts: ChildrenOutletContexts, currentSnapshot: RouterStateSnapshot,
20-
moduleInjector: Injector,
21-
forwardEvent?: (evt: Event) => void): OperatorFunction<RouterStateSnapshot, PreActivation> {
22-
return function(source: Observable<RouterStateSnapshot>) {
23-
return source.pipe(map(snapshot => {
24-
const preActivation =
25-
new PreActivation(snapshot, currentSnapshot, moduleInjector, forwardEvent);
26-
preActivation.initialize(rootContexts);
27-
return preActivation;
28-
}));
29-
};
30-
}
18+
export const setupPreactivation =
19+
(rootContexts: ChildrenOutletContexts, currentSnapshot: RouterStateSnapshot,
20+
moduleInjector: Injector, forwardEvent?: (evt: Event) => void) =>
21+
map((snapshot: RouterStateSnapshot) => {
22+
const preActivation =
23+
new PreActivation(snapshot, currentSnapshot, moduleInjector, forwardEvent);
24+
preActivation.initialize(rootContexts);
25+
return preActivation;
26+
});
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @license
3+
* Copyright Google Inc. All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {MonoTypeOperatorFunction, ObservableInput, from} from 'rxjs';
10+
import {map, switchMap} from 'rxjs/operators';
11+
12+
/**
13+
* Perform a side effect through a switchMap for every emission on the source Observable,
14+
* but return an Observable that is identical to the source. It's essentially the same as
15+
* the `tap` operator, but if the side effectful `next` function returns an ObservableInput,
16+
* it will wait before continuing with the original value.
17+
*/
18+
export function switchTap<T>(next: (x: T) => void|ObservableInput<any>):
19+
MonoTypeOperatorFunction<T> {
20+
return function(source) {
21+
return source.pipe(switchMap(v => {
22+
const nextResult = next(v);
23+
if (nextResult) {
24+
return from(nextResult).pipe(map(() => v));
25+
}
26+
return from([v]);
27+
}));
28+
};
29+
}

0 commit comments

Comments
 (0)