Skip to content

Commit

Permalink
refactor(router): move routing into a single Observable stream (#25740)
Browse files Browse the repository at this point in the history
This is a major refactor of how the router previously worked. There are a couple major advantages of this refactor, and future work will be built on top of it.

First, we will no longer have multiple navigations running at the same time. Previously, a new navigation wouldn't cause the old navigation to be cancelled and cleaned up. Instead, multiple navigations could be going at once, and we imperatively checked that we were operating on the most current `router.navigationId` as we progressed through the Observable streams. This had some major faults, the biggest of which was async races where an ongoing async action could result in a redirect once the async action completed, but there was no way to guarantee there weren't also other redirects that would be queued up by other async actions. After this refactor, there's a single Observable stream that will get cleaned up each time a new navigation is requested.

Additionally, the individual pieces of routing have been pulled out into their own operators. While this was needed in order to create one continuous stream, it also will allow future improvements to the testing APIs as things such as Guards or Resolvers should now be able to be tested in much more isolation.

* Add the new `router.transitions` observable of the new `NavigationTransition` type to contain the transition information
* Update `router.navigations` to pipe off of `router.transitions`
* Re-write navigation Observable flow to a single configured stream
* Refactor `switchMap` instead of the previous `mergeMap` to ensure new navigations cause a cancellation and cleanup of already running navigations
* Wire in existing error and cancellation logic so cancellation matches previous behavior

PR Close #25740
  • Loading branch information
jasonaden authored and kara committed Sep 21, 2018
1 parent 5d68946 commit 4bb10d2
Show file tree
Hide file tree
Showing 12 changed files with 415 additions and 364 deletions.
2 changes: 1 addition & 1 deletion packages/router/src/index.ts
Expand Up @@ -14,7 +14,7 @@ export {RouterOutlet} from './directives/router_outlet';
export {ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, Event, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouterEvent, RoutesRecognized, Scroll} from './events';
export {CanActivate, CanActivateChild, CanDeactivate, CanLoad, Resolve} from './interfaces';
export {DetachedRouteHandle, RouteReuseStrategy} from './route_reuse_strategy';
export {NavigationExtras, Router} from './router';
export {NavigationExtras, NavigationTransition, 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';
Expand Down
24 changes: 10 additions & 14 deletions packages/router/src/operators/after_preactivation.ts
Expand Up @@ -9,21 +9,17 @@
import {MonoTypeOperatorFunction} from 'rxjs';
import {map, mergeMap} from 'rxjs/operators';

import {RouterHook} from '../router';
import {RouterStateSnapshot} from '../router_state';
import {UrlTree} from '../url_tree';
import {NavigationTransition, RouterHook} from '../router';

export function afterPreactivation(
hook: RouterHook, navigationId: number, appliedUrlTree: UrlTree, rawUrlTree: UrlTree,
skipLocationChange: boolean, replaceUrl: boolean):
MonoTypeOperatorFunction<{appliedUrl: UrlTree, snapshot: RouterStateSnapshot}> {
export function afterPreactivation(hook: RouterHook):
MonoTypeOperatorFunction<NavigationTransition> {
return function(source) {
return source.pipe(mergeMap(
p => hook(
p.snapshot,
{
navigationId, appliedUrlTree, rawUrlTree, skipLocationChange, replaceUrl,
})
.pipe(map(() => p))));
return source.pipe(mergeMap(t => hook(t.targetSnapshot !, {
navigationId: t.id,
appliedUrlTree: t.extractedUrl,
rawUrlTree: t.rawUrl,
skipLocationChange: !!t.extras.skipLocationChange,
replaceUrl: !!t.extras.replaceUrl,
}).pipe(map(() => t))));
};
}
20 changes: 8 additions & 12 deletions packages/router/src/operators/apply_redirects.ts
Expand Up @@ -7,25 +7,21 @@
*/

import {Injector} from '@angular/core';
import {Observable, OperatorFunction} from 'rxjs';
import {flatMap} from 'rxjs/operators';
import {MonoTypeOperatorFunction, Observable} from 'rxjs';
import {flatMap, map} from 'rxjs/operators';

import {applyRedirects as applyRedirectsFn} from '../apply_redirects';
import {Routes} from '../config';
import {NavigationTransition} from '../router';
import {RouterConfigLoader} from '../router_config_loader';
import {UrlSerializer, UrlTree} from '../url_tree';
import {UrlSerializer} from '../url_tree';


/**
* Returns the `UrlTree` with the redirection applied.
*
* Lazy modules are loaded along the way.
*/
export function applyRedirects(
moduleInjector: Injector, configLoader: RouterConfigLoader, urlSerializer: UrlSerializer,
config: Routes): OperatorFunction<UrlTree, UrlTree> {
return function(source: Observable<UrlTree>) {
config: Routes): MonoTypeOperatorFunction<NavigationTransition> {
return function(source: Observable<NavigationTransition>) {
return source.pipe(flatMap(
urlTree => applyRedirectsFn(moduleInjector, configLoader, urlSerializer, urlTree, config)));
t => applyRedirectsFn(moduleInjector, configLoader, urlSerializer, t.extractedUrl, config)
.pipe(map(url => ({...t, urlAfterRedirects: url})))));
};
}
24 changes: 10 additions & 14 deletions packages/router/src/operators/before_preactivation.ts
Expand Up @@ -9,21 +9,17 @@
import {MonoTypeOperatorFunction} from 'rxjs';
import {map, mergeMap} from 'rxjs/operators';

import {RouterHook} from '../router';
import {RouterStateSnapshot} from '../router_state';
import {UrlTree} from '../url_tree';
import {NavigationTransition, RouterHook} from '../router';

export function beforePreactivation(
hook: RouterHook, navigationId: number, appliedUrlTree: UrlTree, rawUrlTree: UrlTree,
skipLocationChange: boolean, replaceUrl: boolean):
MonoTypeOperatorFunction<{appliedUrl: UrlTree, snapshot: RouterStateSnapshot}> {
export function beforePreactivation(hook: RouterHook):
MonoTypeOperatorFunction<NavigationTransition> {
return function(source) {
return source.pipe(mergeMap(
p => hook(
p.snapshot,
{
navigationId, appliedUrlTree, rawUrlTree, skipLocationChange, replaceUrl,
})
.pipe(map(() => p))));
return source.pipe(mergeMap(t => hook(t.targetSnapshot !, {
navigationId: t.id,
appliedUrlTree: t.extractedUrl,
rawUrlTree: t.rawUrl,
skipLocationChange: !!t.extras.skipLocationChange,
replaceUrl: !!t.extras.replaceUrl,
}).pipe(map(() => t))));
};
}
29 changes: 13 additions & 16 deletions packages/router/src/operators/check_guards.ts
Expand Up @@ -6,22 +6,19 @@
* found in the LICENSE file at https://angular.io/license
*/

import {Injector, Type} from '@angular/core';
import {Observable, OperatorFunction} from 'rxjs';
import {mergeMap} from 'rxjs/operators';
import {MonoTypeOperatorFunction, Observable, from, of } from 'rxjs';
import {map, mergeMap} from 'rxjs/operators';

import {Route} from '../config';
import {PreActivation} from '../pre_activation';
import {recognize as recognizeFn} from '../recognize';
import {ChildrenOutletContexts} from '../router_outlet_context';
import {RouterStateSnapshot} from '../router_state';
import {UrlTree} from '../url_tree';
import {NavigationTransition} from '../router';

export function checkGuards(
rootContexts: ChildrenOutletContexts, currentSnapshot: RouterStateSnapshot,
moduleInjector: Injector, preActivation: PreActivation): OperatorFunction<UrlTree, boolean> {
return function(source: Observable<UrlTree>) {
return source.pipe(
mergeMap((appliedUrl): Observable<boolean> => { return preActivation.checkGuards(); }));
export function checkGuards(): MonoTypeOperatorFunction<NavigationTransition> {
return function(source: Observable<NavigationTransition>) {

return source.pipe(mergeMap(t => {
if (!t.preActivation) {
throw 'Initialized PreActivation required to check guards';
}
return t.preActivation.checkGuards().pipe(map(guardsResult => ({...t, guardsResult})));
}));
};
}
}
23 changes: 23 additions & 0 deletions packages/router/src/operators/mergeMapIf.ts
@@ -0,0 +1,23 @@
/**
* @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 {EMPTY, MonoTypeOperatorFunction, Observable, of } from 'rxjs';
import {mergeMap} from 'rxjs/operators';

export function mergeMapIf<T>(
predicate: (value: T) => boolean, tap: (value: T) => any): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => {
return source.pipe(mergeMap(s => {
if (predicate(s)) {
tap(s);
return EMPTY;
}
return of (s);
}));
};
}
17 changes: 9 additions & 8 deletions packages/router/src/operators/recognize.ts
Expand Up @@ -7,22 +7,23 @@
*/

import {Type} from '@angular/core';
import {Observable, OperatorFunction} from 'rxjs';
import {mergeMap} from 'rxjs/operators';
import {MonoTypeOperatorFunction, Observable} from 'rxjs';
import {map, mergeMap} from 'rxjs/operators';

import {Route} from '../config';
import {recognize as recognizeFn} from '../recognize';
import {RouterStateSnapshot} from '../router_state';
import {NavigationTransition} from '../router';
import {UrlTree} from '../url_tree';

export function recognize(
rootComponentType: Type<any>| null, config: Route[], serializer: (url: UrlTree) => string,
paramsInheritanceStrategy: 'emptyOnly' |
'always'): OperatorFunction<UrlTree, RouterStateSnapshot> {
return function(source: Observable<UrlTree>) {
'always'): MonoTypeOperatorFunction<NavigationTransition> {
return function(source: Observable<NavigationTransition>) {
return source.pipe(mergeMap(
(appliedUrl: UrlTree) => recognizeFn(
rootComponentType, config, appliedUrl, serializer(appliedUrl),
paramsInheritanceStrategy)));
t => recognizeFn(
rootComponentType, config, t.urlAfterRedirects, serializer(t.extractedUrl),
paramsInheritanceStrategy)
.pipe(map(targetSnapshot => ({...t, targetSnapshot})))));
};
}
26 changes: 11 additions & 15 deletions packages/router/src/operators/resolve_data.ts
Expand Up @@ -6,23 +6,19 @@
* found in the LICENSE file at https://angular.io/license
*/

import {Injector, Type} from '@angular/core';
import {Observable, OperatorFunction} from 'rxjs';
import {mergeMap} from 'rxjs/operators';
import {MonoTypeOperatorFunction, Observable, OperatorFunction, from, of } from 'rxjs';
import {map, mergeMap} from 'rxjs/operators';

import {Route} from '../config';
import {PreActivation} from '../pre_activation';
import {recognize as recognizeFn} from '../recognize';
import {ChildrenOutletContexts} from '../router_outlet_context';
import {RouterStateSnapshot} from '../router_state';
import {UrlTree} from '../url_tree';
import {NavigationTransition} from '../router';

export function resolveData(
preActivation: PreActivation,
paramsInheritanceStrategy: 'emptyOnly' | 'always'): OperatorFunction<UrlTree, boolean> {
return function(source: Observable<UrlTree>) {
return source.pipe(mergeMap((appliedUrl): Observable<boolean> => {
return preActivation.resolveData(paramsInheritanceStrategy);
paramsInheritanceStrategy: 'emptyOnly' | 'always'): MonoTypeOperatorFunction<NavigationTransition> {
return function(source: Observable<NavigationTransition>) {
return source.pipe(mergeMap(t => {
if (!t.preActivation) {
throw 'Initialized PreActivation required to check guards';
}
return t.preActivation.resolveData(paramsInheritanceStrategy).pipe(map(_ => t));
}));
};
}
}
26 changes: 26 additions & 0 deletions packages/router/src/operators/throwIf.ts
@@ -0,0 +1,26 @@
/**
* @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 {MonoTypeOperatorFunction, Observable} from 'rxjs';
import {tap} from 'rxjs/operators';

export function throwIf<T>(
predicate: (value: T) => boolean,
errorFactory: (() => any) = defaultErrorFactory): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => {
return source.pipe(tap(s => {
if (predicate(s)) {
throw errorFactory();
}
}));
};
}

function defaultErrorFactory() {
return new Error();
}

0 comments on commit 4bb10d2

Please sign in to comment.