From a0a6029915bb36b715efc044c688e7148841bbe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matias=20Niemel=C3=A4?= Date: Thu, 18 May 2017 11:28:39 -0700 Subject: [PATCH] revert: refactor(router): don't run the change detection every time an outlet is activated This reverts commit 198edb31093ffdecfd13aed17967fb02e650cffe. --- .../router/src/directives/router_outlet.ts | 79 ++++--- packages/router/src/index.ts | 2 +- packages/router/src/route_reuse_strategy.ts | 8 +- packages/router/src/router.ts | 203 +++++++++--------- packages/router/src/router_module.ts | 14 +- packages/router/src/router_outlet_context.ts | 80 ------- packages/router/src/router_outlet_map.ts | 29 +++ packages/router/test/integration.spec.ts | 66 +++--- packages/router/test/router.spec.ts | 4 +- .../testing/src/router_testing_module.ts | 10 +- tools/public_api_guard/router/router.d.ts | 36 ++-- 11 files changed, 232 insertions(+), 299 deletions(-) delete mode 100644 packages/router/src/router_outlet_context.ts create mode 100644 packages/router/src/router_outlet_map.ts diff --git a/packages/router/src/directives/router_outlet.ts b/packages/router/src/directives/router_outlet.ts index 207850b76f..9c8082b8b6 100644 --- a/packages/router/src/directives/router_outlet.ts +++ b/packages/router/src/directives/router_outlet.ts @@ -6,8 +6,8 @@ * found in the LICENSE file at https://angular.io/license */ -import {Attribute, ComponentFactoryResolver, ComponentRef, Directive, EventEmitter, Injector, OnDestroy, OnInit, Output, ViewContainerRef} from '@angular/core'; -import {ChildrenOutletContexts} from '../router_outlet_context'; +import {Attribute, ComponentFactoryResolver, ComponentRef, Directive, EventEmitter, Injector, OnDestroy, Output, ReflectiveInjector, ResolvedReflectiveProvider, ViewContainerRef} from '@angular/core'; +import {RouterOutletMap} from '../router_outlet_map'; import {ActivatedRoute} from '../router_state'; import {PRIMARY_OUTLET} from '../shared'; @@ -36,39 +36,23 @@ import {PRIMARY_OUTLET} from '../shared'; * @stable */ @Directive({selector: 'router-outlet'}) -export class RouterOutlet implements OnDestroy, OnInit { +export class RouterOutlet implements OnDestroy { private activated: ComponentRef|null = null; private _activatedRoute: ActivatedRoute|null = null; - private name: string; + private _outletName: string; + public outletMap: RouterOutletMap; @Output('activate') activateEvents = new EventEmitter(); @Output('deactivate') deactivateEvents = new EventEmitter(); constructor( - private parentContexts: ChildrenOutletContexts, private location: ViewContainerRef, + private parentOutletMap: RouterOutletMap, private location: ViewContainerRef, private resolver: ComponentFactoryResolver, @Attribute('name') name: string) { - this.name = name || PRIMARY_OUTLET; - parentContexts.onChildOutletCreated(this.name, this); + this._outletName = name || PRIMARY_OUTLET; + parentOutletMap.registerOutlet(this._outletName, this); } - ngOnDestroy(): void { this.parentContexts.onChildOutletDestroyed(this.name); } - - ngOnInit(): void { - if (!this.activated) { - // If the outlet was not instantiated at the time the route got activated we need to populate - // the outlet when it is initialized. - const context = this.parentContexts.getContext(this.name); - if (context && context.route) { - if (context.attachRef) { - // `attachRef` is populated when there is an existing component to mount - this.attach(context.attachRef, context.route); - } else { - // otherwise the component defined in the configuration is created - this.activateWith(context.route, context.resolver || null); - } - } - } - } + ngOnDestroy(): void { this.parentOutletMap.removeOutlet(this._outletName); } /** @deprecated since v4 **/ get locationInjector(): Injector { return this.location.injector; } @@ -118,34 +102,65 @@ export class RouterOutlet implements OnDestroy, OnInit { } } - activateWith(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver|null) { + /** @deprecated since v4, use {@link #activateWith} */ + activate( + activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver, injector: Injector, + providers: ResolvedReflectiveProvider[], outletMap: RouterOutletMap): void { if (this.isActivated) { throw new Error('Cannot activate an already activated outlet'); } + + this.outletMap = outletMap; this._activatedRoute = activatedRoute; + + const snapshot = activatedRoute._futureSnapshot; + const component: any = snapshot._routeConfig !.component; + const factory = resolver.resolveComponentFactory(component) !; + + const inj = ReflectiveInjector.fromResolvedProviders(providers, injector); + + this.activated = this.location.createComponent(factory, this.location.length, inj, []); + this.activated.changeDetectorRef.detectChanges(); + + this.activateEvents.emit(this.activated.instance); + } + + activateWith( + activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver|null, + outletMap: RouterOutletMap) { + if (this.isActivated) { + throw new Error('Cannot activate an already activated outlet'); + } + + this.outletMap = outletMap; + this._activatedRoute = activatedRoute; + const snapshot = activatedRoute._futureSnapshot; const component = snapshot._routeConfig !.component; + resolver = resolver || this.resolver; const factory = resolver.resolveComponentFactory(component); - const childContexts = this.parentContexts.getOrCreateContext(this.name).children; - const injector = new OutletInjector(activatedRoute, childContexts, this.location.injector); + + const injector = new OutletInjector(activatedRoute, outletMap, this.location.injector); + this.activated = this.location.createComponent(factory, this.location.length, injector); + this.activated.changeDetectorRef.detectChanges(); + this.activateEvents.emit(this.activated.instance); } } class OutletInjector implements Injector { constructor( - private route: ActivatedRoute, private childContexts: ChildrenOutletContexts, - private parent: Injector) {} + private route: ActivatedRoute, private map: RouterOutletMap, private parent: Injector) {} get(token: any, notFoundValue?: any): any { if (token === ActivatedRoute) { return this.route; } - if (token === ChildrenOutletContexts) { - return this.childContexts; + if (token === RouterOutletMap) { + return this.map; } return this.parent.get(token, notFoundValue); diff --git a/packages/router/src/index.ts b/packages/router/src/index.ts index f4924f47f8..6e329cf2be 100644 --- a/packages/router/src/index.ts +++ b/packages/router/src/index.ts @@ -17,7 +17,7 @@ export {DetachedRouteHandle, RouteReuseStrategy} from './route_reuse_strategy'; export {NavigationExtras, 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'; +export {RouterOutletMap} from './router_outlet_map'; export {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader'; export {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot} from './router_state'; export {PRIMARY_OUTLET, ParamMap, Params, convertToParamMap} from './shared'; diff --git a/packages/router/src/route_reuse_strategy.ts b/packages/router/src/route_reuse_strategy.ts index 6f142e045d..45da2d6164 100644 --- a/packages/router/src/route_reuse_strategy.ts +++ b/packages/router/src/route_reuse_strategy.ts @@ -8,7 +8,6 @@ import {ComponentRef} from '@angular/core'; -import {OutletContext} from './router_outlet_context'; import {ActivatedRoute, ActivatedRouteSnapshot} from './router_state'; import {TreeNode} from './utils/tree'; @@ -24,7 +23,6 @@ export type DetachedRouteHandle = {}; /** @internal */ export type DetachedRouteHandleInternal = { - contexts: Map, componentRef: ComponentRef, route: TreeNode, }; @@ -38,11 +36,7 @@ export abstract class RouteReuseStrategy { /** Determines if this route (and its subtree) should be detached to be reused later */ abstract shouldDetach(route: ActivatedRouteSnapshot): boolean; - /** - * Stores the detached route. - * - * Storing a `null` value should erase the previously stored value. - */ + /** Stores the detached route */ abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle|null): void; /** Determines if this route (and its subtree) should be reattached */ diff --git a/packages/router/src/router.ts b/packages/router/src/router.ts index 2a7936a140..48b9f3f020 100644 --- a/packages/router/src/router.ts +++ b/packages/router/src/router.ts @@ -25,13 +25,14 @@ import {applyRedirects} from './apply_redirects'; import {LoadedRouterConfig, QueryParamsHandling, ResolveData, Route, Routes, RunGuardsAndResolvers, validateConfig} from './config'; import {createRouterState} from './create_router_state'; import {createUrlTree} from './create_url_tree'; +import {RouterOutlet} from './directives/router_outlet'; import {Event, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, RouteConfigLoadEnd, RouteConfigLoadStart, RoutesRecognized} from './events'; import {recognize} from './recognize'; import {DefaultRouteReuseStrategy, DetachedRouteHandleInternal, RouteReuseStrategy} from './route_reuse_strategy'; import {RouterConfigLoader} from './router_config_loader'; -import {ChildrenOutletContexts, OutletContext} from './router_outlet_context'; +import {RouterOutletMap} from './router_outlet_map'; import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, advanceActivatedRoute, createEmptyState, equalParamsAndUrlSegments, inheritedParamsDataResolve} from './router_state'; -import {Params, isNavigationCancelingError} from './shared'; +import {PRIMARY_OUTLET, Params, isNavigationCancelingError} from './shared'; import {DefaultUrlHandlingStrategy, UrlHandlingStrategy} from './url_handling_strategy'; import {UrlSerializer, UrlTree, containsTree, createEmptyUrlTree} from './url_tree'; import {andObservables, forEach, shallowEqual, waitForMap, wrapIntoObservable} from './utils/collection'; @@ -250,7 +251,7 @@ export class Router { // TODO: vsavkin make internal after the final is out. constructor( private rootComponentType: Type|null, private urlSerializer: UrlSerializer, - private rootContexts: ChildrenOutletContexts, private location: Location, injector: Injector, + private outletMap: RouterOutletMap, private location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, public config: Routes) { const onLoadStart = (r: Route) => this.triggerEvent(new RouteConfigLoadStart(r)); const onLoadEnd = (r: Route) => this.triggerEvent(new RouteConfigLoadEnd(r)); @@ -630,7 +631,7 @@ export class Router { const moduleInjector = this.ngModule.injector; preActivation = new PreActivation(snapshot, this.currentRouterState.snapshot, moduleInjector); - preActivation.traverse(this.rootContexts); + preActivation.traverse(this.outletMap); return {appliedUrl, snapshot}; }); @@ -701,7 +702,7 @@ export class Router { } new ActivateRoutes(this.routeReuseStrategy, state, storedState) - .activate(this.rootContexts); + .activate(this.outletMap); navigationIsSuccessful = true; }) @@ -766,10 +767,10 @@ export class PreActivation { private future: RouterStateSnapshot, private curr: RouterStateSnapshot, private moduleInjector: Injector) {} - traverse(parentContexts: ChildrenOutletContexts): void { + traverse(parentOutletMap: RouterOutletMap): void { const futureRoot = this.future._root; const currRoot = this.curr ? this.curr._root : null; - this.traverseChildRoutes(futureRoot, currRoot, parentContexts, [futureRoot.value]); + this.traverseChildRoutes(futureRoot, currRoot, parentOutletMap, [futureRoot.value]); } checkGuards(): Observable { @@ -792,35 +793,34 @@ export class PreActivation { private traverseChildRoutes( futureNode: TreeNode, currNode: TreeNode|null, - contexts: ChildrenOutletContexts|null, futurePath: ActivatedRouteSnapshot[]): void { + outletMap: RouterOutletMap|null, futurePath: ActivatedRouteSnapshot[]): void { const prevChildren = nodeChildrenAsMap(currNode); // Process the children of the future route futureNode.children.forEach(c => { - this.traverseRoutes(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value])); + this.traverseRoutes(c, prevChildren[c.value.outlet], outletMap, futurePath.concat([c.value])); delete prevChildren[c.value.outlet]; }); // Process any children left from the current route (not active for the future route) forEach( prevChildren, (v: TreeNode, k: string) => - this.deactivateRouteAndItsChildren(v, contexts !.getContext(k))); + this.deactivateRouteAndItsChildren(v, outletMap !._outlets[k])); } private traverseRoutes( futureNode: TreeNode, currNode: TreeNode, - parentContexts: ChildrenOutletContexts|null, futurePath: ActivatedRouteSnapshot[]): void { + parentOutletMap: RouterOutletMap|null, futurePath: ActivatedRouteSnapshot[]): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; - const context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null; + const outlet = parentOutletMap ? parentOutletMap._outlets[futureNode.value.outlet] : null; // reusing the node if (curr && future._routeConfig === curr._routeConfig) { if (this.shouldRunGuardsAndResolvers( curr, future, future._routeConfig !.runGuardsAndResolvers)) { this.canActivateChecks.push(new CanActivate(futurePath)); - const outlet = context !.outlet !; - this.canDeactivateChecks.push(new CanDeactivate(outlet.component, curr)); + this.canDeactivateChecks.push(new CanDeactivate(outlet !.component, curr)); } else { // we need to set the data future.data = curr.data; @@ -830,25 +830,25 @@ export class PreActivation { // If we have a component, we need to go through an outlet. if (future.component) { this.traverseChildRoutes( - futureNode, currNode, context ? context.children : null, futurePath); + futureNode, currNode, outlet ? outlet.outletMap : null, futurePath); // if we have a componentless route, we recurse but keep the same outlet map. } else { - this.traverseChildRoutes(futureNode, currNode, parentContexts, futurePath); + this.traverseChildRoutes(futureNode, currNode, parentOutletMap, futurePath); } } else { if (curr) { - this.deactivateRouteAndItsChildren(currNode, context); + this.deactivateRouteAndItsChildren(currNode, outlet); } this.canActivateChecks.push(new CanActivate(futurePath)); // If we have a component, we need to go through an outlet. if (future.component) { - this.traverseChildRoutes(futureNode, null, context ? context.children : null, futurePath); + this.traverseChildRoutes(futureNode, null, outlet ? outlet.outletMap : null, futurePath); // if we have a componentless route, we recurse but keep the same outlet map. } else { - this.traverseChildRoutes(futureNode, null, parentContexts, futurePath); + this.traverseChildRoutes(futureNode, null, parentOutletMap, futurePath); } } } @@ -871,24 +871,24 @@ export class PreActivation { } private deactivateRouteAndItsChildren( - route: TreeNode, context: OutletContext|null): void { - const children = nodeChildrenAsMap(route); + route: TreeNode, outlet: RouterOutlet|null): void { + const prevChildren = nodeChildrenAsMap(route); const r = route.value; - forEach(children, (node: TreeNode, childName: string) => { + forEach(prevChildren, (v: TreeNode, k: string) => { if (!r.component) { - this.deactivateRouteAndItsChildren(node, context); - } else if (context) { - this.deactivateRouteAndItsChildren(node, context.children.getContext(childName)); + this.deactivateRouteAndItsChildren(v, outlet); + } else if (outlet) { + this.deactivateRouteAndItsChildren(v, outlet.outletMap._outlets[k]); } else { - this.deactivateRouteAndItsChildren(node, null); + this.deactivateRouteAndItsChildren(v, null); } }); if (!r.component) { this.canDeactivateChecks.push(new CanDeactivate(null, r)); - } else if (context && context.outlet && context.outlet.isActivated) { - this.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r)); + } else if (outlet && outlet.isActivated) { + this.canDeactivateChecks.push(new CanDeactivate(outlet.component, r)); } else { this.canDeactivateChecks.push(new CanDeactivate(null, r)); } @@ -1002,109 +1002,103 @@ class ActivateRoutes { private routeReuseStrategy: RouteReuseStrategy, private futureState: RouterState, private currState: RouterState) {} - activate(parentContexts: ChildrenOutletContexts): void { + activate(parentOutletMap: RouterOutletMap): void { const futureRoot = this.futureState._root; const currRoot = this.currState ? this.currState._root : null; - this.deactivateChildRoutes(futureRoot, currRoot, parentContexts); + this.deactivateChildRoutes(futureRoot, currRoot, parentOutletMap); advanceActivatedRoute(this.futureState.root); - this.activateChildRoutes(futureRoot, currRoot, parentContexts); + this.activateChildRoutes(futureRoot, currRoot, parentOutletMap); } // De-activate the child route that are not re-used for the future state private deactivateChildRoutes( futureNode: TreeNode, currNode: TreeNode|null, - contexts: ChildrenOutletContexts): void { - const children: {[outletName: string]: TreeNode} = nodeChildrenAsMap(currNode); + outletMap: RouterOutletMap): void { + const prevChildren: {[outlet: string]: any} = nodeChildrenAsMap(currNode); // Recurse on the routes active in the future state to de-activate deeper children - futureNode.children.forEach(futureChild => { - const childOutletName = futureChild.value.outlet; - this.deactivateRoutes(futureChild, children[childOutletName], contexts); - delete children[childOutletName]; + futureNode.children.forEach(child => { + const childOutletName = child.value.outlet; + this.deactivateRoutes(child, prevChildren[childOutletName], outletMap); + delete prevChildren[childOutletName]; }); // De-activate the routes that will not be re-used - forEach(children, (v: TreeNode, childName: string) => { - this.deactivateRouteAndItsChildren(v, contexts); - }); + forEach(prevChildren, (v: any, k: string) => this.deactivateRouteAndItsChildren(v, outletMap)); } private deactivateRoutes( futureNode: TreeNode, currNode: TreeNode, - parentContext: ChildrenOutletContexts): void { + parentOutletMap: RouterOutletMap): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; if (future === curr) { - // Reusing the node, check to see if the children need to be de-activated + // Reusing the node, check to see of the children need to be de-activated if (future.component) { // If we have a normal route, we need to go through an outlet. - const context = parentContext.getContext(future.outlet); - if (context) { - this.deactivateChildRoutes(futureNode, currNode, context.children); - } + const outlet = getOutlet(parentOutletMap, future); + this.deactivateChildRoutes(futureNode, currNode, outlet.outletMap); } else { // if we have a componentless route, we recurse but keep the same outlet map. - this.deactivateChildRoutes(futureNode, currNode, parentContext); + this.deactivateChildRoutes(futureNode, currNode, parentOutletMap); } } else { if (curr) { - // Deactivate the current route which will not be re-used - this.deactivateRouteAndItsChildren(currNode, parentContext); + this.deactivateRouteAndItsChildren(currNode, parentOutletMap); } } } private deactivateRouteAndItsChildren( - route: TreeNode, parentContexts: ChildrenOutletContexts): void { + route: TreeNode, parentOutletMap: RouterOutletMap): void { if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) { - this.detachAndStoreRouteSubtree(route, parentContexts); + this.detachAndStoreRouteSubtree(route, parentOutletMap); } else { - this.deactivateRouteAndOutlet(route, parentContexts); + this.deactivateRouteAndOutlet(route, parentOutletMap); } } private detachAndStoreRouteSubtree( - route: TreeNode, parentContexts: ChildrenOutletContexts): void { - const context = parentContexts.getContext(route.value.outlet); - if (context && context.outlet) { - const componentRef = context.outlet.detach(); - const contexts = context.children.onOutletDeactivated(); - this.routeReuseStrategy.store(route.value.snapshot, {componentRef, route, contexts}); - } + route: TreeNode, parentOutletMap: RouterOutletMap): void { + const outlet = getOutlet(parentOutletMap, route.value); + const componentRef = outlet.detach(); + this.routeReuseStrategy.store(route.value.snapshot, {componentRef, route}); } private deactivateRouteAndOutlet( - route: TreeNode, parentContexts: ChildrenOutletContexts): void { - const context = parentContexts.getContext(route.value.outlet); + route: TreeNode, parentOutletMap: RouterOutletMap): void { + const prevChildren: {[outletName: string]: any} = nodeChildrenAsMap(route); + let outlet: RouterOutlet; - if (context) { - const children: {[outletName: string]: any} = nodeChildrenAsMap(route); - const contexts = route.value.component ? context.children : parentContexts; - - forEach(children, (v: any, k: string) => {this.deactivateRouteAndItsChildren(v, contexts)}); - - if (context.outlet) { - // Destroy the component - context.outlet.deactivate(); - // Destroy the contexts for all the outlets that were in the component - context.children.onOutletDeactivated(); - } + // getOutlet throws when cannot find the right outlet, + // which can happen if an outlet was in an NgIf and was removed + try { + outlet = getOutlet(parentOutletMap, route.value); + } catch (e) { + return; } + + const outletMap = route.value.component ? outlet.outletMap : parentOutletMap; + + forEach( + prevChildren, (v: any, k: string) => { this.deactivateRouteAndItsChildren(v, outletMap); }); + + outlet.deactivate(); } private activateChildRoutes( futureNode: TreeNode, currNode: TreeNode|null, - contexts: ChildrenOutletContexts): void { - const children: {[outlet: string]: any} = nodeChildrenAsMap(currNode); + outletMap: RouterOutletMap): void { + const prevChildren: {[outlet: string]: any} = nodeChildrenAsMap(currNode); futureNode.children.forEach( - c => { this.activateRoutes(c, children[c.value.outlet], contexts); }); + c => { this.activateRoutes(c, prevChildren[c.value.outlet], outletMap); }); } private activateRoutes( futureNode: TreeNode, currNode: TreeNode, - parentContexts: ChildrenOutletContexts): void { + parentOutletMap: RouterOutletMap): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; @@ -1114,50 +1108,42 @@ class ActivateRoutes { if (future === curr) { if (future.component) { // If we have a normal route, we need to go through an outlet. - const context = parentContexts.getOrCreateContext(future.outlet); - this.activateChildRoutes(futureNode, currNode, context.children); + const outlet = getOutlet(parentOutletMap, future); + this.activateChildRoutes(futureNode, currNode, outlet.outletMap); } else { // if we have a componentless route, we recurse but keep the same outlet map. - this.activateChildRoutes(futureNode, currNode, parentContexts); + this.activateChildRoutes(futureNode, currNode, parentOutletMap); } } else { if (future.component) { // if we have a normal route, we need to place the component into the outlet and recurse. - const context = parentContexts.getOrCreateContext(future.outlet); + const outlet = getOutlet(parentOutletMap, futureNode.value); if (this.routeReuseStrategy.shouldAttach(future.snapshot)) { const stored = (this.routeReuseStrategy.retrieve(future.snapshot)); this.routeReuseStrategy.store(future.snapshot, null); - context.children.onOutletReAttached(stored.contexts); - context.attachRef = stored.componentRef; - context.route = stored.route.value; - if (context.outlet) { - // Attach right away when the outlet has already been instantiated - // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated - context.outlet.attach(stored.componentRef, stored.route.value); - } + outlet.attach(stored.componentRef, stored.route.value); advanceActivatedRouteNodeAndItsChildren(stored.route); } else { - const config = parentLoadedConfig(future.snapshot); - const cmpFactoryResolver = config ? config.module.componentFactoryResolver : null; - - context.route = future; - context.resolver = cmpFactoryResolver; - if (context.outlet) { - // Activate the outlet when it has already been instantiated - // Otherwise it will get activated from its `ngOnInit` when instantiated - context.outlet.activateWith(future, cmpFactoryResolver); - } - - this.activateChildRoutes(futureNode, null, context.children); + const outletMap = new RouterOutletMap(); + this.placeComponentIntoOutlet(outletMap, future, outlet); + this.activateChildRoutes(futureNode, null, outletMap); } } else { // if we have a componentless route, we recurse but keep the same outlet map. - this.activateChildRoutes(futureNode, null, parentContexts); + this.activateChildRoutes(futureNode, null, parentOutletMap); } } } + + private placeComponentIntoOutlet( + outletMap: RouterOutletMap, future: ActivatedRoute, outlet: RouterOutlet): void { + const config = parentLoadedConfig(future.snapshot); + const cmpFactoryResolver = config ? config.module.componentFactoryResolver : null; + + outlet.activateWith(future, cmpFactoryResolver, outletMap); + } } function advanceActivatedRouteNodeAndItsChildren(node: TreeNode): void { @@ -1197,6 +1183,19 @@ function nodeChildrenAsMap(node: TreeNode| null) { return map; } +function getOutlet(outletMap: RouterOutletMap, route: ActivatedRoute): RouterOutlet { + const outlet = outletMap._outlets[route.outlet]; + if (!outlet) { + const componentName = (route.component).name; + if (route.outlet === PRIMARY_OUTLET) { + throw new Error(`Cannot find primary outlet to load '${componentName}'`); + } else { + throw new Error(`Cannot find the outlet ${route.outlet} to load '${componentName}'`); + } + } + return outlet; +} + function validateCommands(commands: string[]): void { for (let i = 0; i < commands.length; i++) { const cmd = commands[i]; diff --git a/packages/router/src/router_module.ts b/packages/router/src/router_module.ts index 8ecec6aff7..a7c1c076ec 100644 --- a/packages/router/src/router_module.ts +++ b/packages/router/src/router_module.ts @@ -19,7 +19,7 @@ import {RouterOutlet} from './directives/router_outlet'; import {RouteReuseStrategy} from './route_reuse_strategy'; import {ErrorHandler, Router} from './router'; import {ROUTES} from './router_config_loader'; -import {ChildrenOutletContexts} from './router_outlet_context'; +import {RouterOutletMap} from './router_outlet_map'; import {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader'; import {ActivatedRoute} from './router_state'; import {UrlHandlingStrategy} from './url_handling_strategy'; @@ -51,12 +51,12 @@ export const ROUTER_PROVIDERS: Provider[] = [ provide: Router, useFactory: setupRouter, deps: [ - ApplicationRef, UrlSerializer, ChildrenOutletContexts, Location, Injector, - NgModuleFactoryLoader, Compiler, ROUTES, ROUTER_CONFIGURATION, - [UrlHandlingStrategy, new Optional()], [RouteReuseStrategy, new Optional()] + ApplicationRef, UrlSerializer, RouterOutletMap, Location, Injector, NgModuleFactoryLoader, + Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()], + [RouteReuseStrategy, new Optional()] ] }, - ChildrenOutletContexts, + RouterOutletMap, {provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]}, {provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader}, RouterPreloader, @@ -270,12 +270,12 @@ export interface ExtraOptions { } export function setupRouter( - ref: ApplicationRef, urlSerializer: UrlSerializer, contexts: ChildrenOutletContexts, + ref: ApplicationRef, urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[][], opts: ExtraOptions = {}, urlHandlingStrategy?: UrlHandlingStrategy, routeReuseStrategy?: RouteReuseStrategy) { const router = new Router( - null, urlSerializer, contexts, location, injector, loader, compiler, flatten(config)); + null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(config)); if (urlHandlingStrategy) { router.urlHandlingStrategy = urlHandlingStrategy; diff --git a/packages/router/src/router_outlet_context.ts b/packages/router/src/router_outlet_context.ts deleted file mode 100644 index 7ceb1f7abb..0000000000 --- a/packages/router/src/router_outlet_context.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @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 {ComponentFactoryResolver, ComponentRef} from '@angular/core'; - -import {RouterOutlet} from './directives/router_outlet'; -import {ActivatedRoute} from './router_state'; - - -/** - * Store contextual information about a {@link RouterOutlet} - * - * @stable - */ -export class OutletContext { - outlet: RouterOutlet|null = null; - route: ActivatedRoute|null = null; - resolver: ComponentFactoryResolver|null = null; - children = new ChildrenOutletContexts(); - attachRef: ComponentRef|null = null; -} - -/** - * Store contextual information about the children (= nested) {@link RouterOutlet} - * - * @stable - */ -export class ChildrenOutletContexts { - // contexts for child outlets, by name. - private contexts = new Map(); - - /** Called when a `RouterOutlet` directive is instantiated */ - onChildOutletCreated(childName: string, outlet: RouterOutlet): void { - const context = this.getOrCreateContext(childName); - context.outlet = outlet; - this.contexts.set(childName, context); - } - - /** - * Called when a `RouterOutlet` directive is destroyed. - * We need to keep the context as the outlet could be destroyed inside a NgIf and might be - * re-created later. - */ - onChildOutletDestroyed(childName: string): void { - const context = this.getContext(childName); - if (context) { - context.outlet = null; - } - } - - /** - * Called when the corresponding route is deactivated during navigation. - * Because the component get destroyed, all children outlet are destroyed. - */ - onOutletDeactivated(): Map { - const contexts = this.contexts; - this.contexts = new Map(); - return contexts; - } - - onOutletReAttached(contexts: Map) { this.contexts = contexts; } - - getOrCreateContext(childName: string): OutletContext { - let context = this.getContext(childName); - - if (!context) { - context = new OutletContext(); - this.contexts.set(childName, context); - } - - return context; - } - - getContext(childName: string): OutletContext|null { return this.contexts.get(childName) || null; } -} diff --git a/packages/router/src/router_outlet_map.ts b/packages/router/src/router_outlet_map.ts new file mode 100644 index 0000000000..f70bc0e814 --- /dev/null +++ b/packages/router/src/router_outlet_map.ts @@ -0,0 +1,29 @@ +/** + * @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 {RouterOutlet} from './directives/router_outlet'; + +/** + * @whatItDoes Contains all the router outlets created in a component. + * + * @stable + */ +export class RouterOutletMap { + /** @internal */ + _outlets: {[name: string]: RouterOutlet} = {}; + + /** + * Adds an outlet to this map. + */ + registerOutlet(name: string, outlet: RouterOutlet): void { this._outlets[name] = outlet; } + + /** + * Removes an outlet from this map. + */ + removeOutlet(name: string): void { this._outlets[name] = undefined as any; } +} diff --git a/packages/router/test/integration.spec.ts b/packages/router/test/integration.spec.ts index f9edf80299..f130aefc5c 100644 --- a/packages/router/test/integration.spec.ts +++ b/packages/router/test/integration.spec.ts @@ -120,10 +120,8 @@ describe('Integration', () => { router.resetConfig([{ path: 'parent/:id', component: Parent, - children: [ - {path: 'child1', component: Child1}, - {path: 'child2', component: Child2}, - ] + children: + [{path: 'child1', component: Child1}, {path: 'child2', component: Child2}] }]); router.navigateByUrl('/parent/1/child1'); @@ -133,18 +131,13 @@ describe('Integration', () => { advance(fixture); expect(location.path()).toEqual('/parent/2/child2'); - expect(log).toEqual([ - {id: '1'}, - 'child1 destroy', - {id: '2'}, - 'child2 constructor', - ]); + expect(log).toEqual([{id: '1'}, 'child1 destroy', {id: '2'}, 'child2 constructor']); }))); }); it('should execute navigations serialy', - fakeAsync(inject([Router, Location], (router: Router) => { + fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ @@ -209,7 +202,7 @@ describe('Integration', () => { router.resetConfig([{ path: 'child', - component: OutletInNgIf, + component: LinkInNgIf, children: [{path: 'simple', component: SimpleCmp}] }]); @@ -219,10 +212,10 @@ describe('Integration', () => { expect(location.path()).toEqual('/child/simple'); }))); - it('should work when an outlet is added/removed', fakeAsync(() => { + it('should work when an outlet is in an ngIf (and is removed)', fakeAsync(() => { @Component({ selector: 'someRoot', - template: `[
]` + template: `
` }) class RootCmpWithLink { cond: boolean = true; @@ -230,25 +223,26 @@ describe('Integration', () => { TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.get(Router); + const location: Location = TestBed.get(Location); const fixture = createRoot(router, RootCmpWithLink); - router.resetConfig([ - {path: 'simple', component: SimpleCmp}, - {path: 'blank', component: BlankCmp}, - ]); + router.resetConfig( + [{path: 'simple', component: SimpleCmp}, {path: 'blank', component: BlankCmp}]); router.navigateByUrl('/simple'); advance(fixture); - expect(fixture.nativeElement).toHaveText('[simple]'); + expect(location.path()).toEqual('/simple'); - fixture.componentInstance.cond = false; + const instance = fixture.componentInstance; + instance.cond = false; advance(fixture); - expect(fixture.nativeElement).toHaveText('[]'); - fixture.componentInstance.cond = true; + let recordedError: any = null; + router.navigateByUrl('/blank') !.catch(e => recordedError = e); advance(fixture); - expect(fixture.nativeElement).toHaveText('[simple]'); + + expect(recordedError.message).toEqual('Cannot find primary outlet to load \'BlankCmp\''); })); it('should update location when navigating', fakeAsync(() => { @@ -3236,17 +3230,15 @@ describe('Integration', () => { shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; } store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {} shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; } - retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null { return null; } + retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return null !; } shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { if (future.routeConfig !== curr.routeConfig) { return false; - } - - if (Object.keys(future.params).length !== Object.keys(curr.params).length) { + } else if (Object.keys(future.params).length !== Object.keys(curr.params).length) { return false; + } else { + return Object.keys(future.params).every(k => future.params[k] === curr.params[k]); } - - return Object.keys(future.params).every(k => future.params[k] === curr.params[k]); } } @@ -3257,12 +3249,8 @@ describe('Integration', () => { router.routeReuseStrategy = new AttachDetachReuseStrategy(); router.resetConfig([ - { - path: 'a', - component: TeamCmp, - children: [{path: 'b', component: SimpleCmp}], - }, - {path: 'c', component: UserCmp}, + {path: 'a', component: TeamCmp, children: [{path: 'b', component: SimpleCmp}]}, + {path: 'c', component: UserCmp} ]); router.navigateByUrl('/a/b'); @@ -3471,7 +3459,7 @@ class RelativeLinkInIfCmp { @Component( {selector: 'child', template: '
'}) -class OutletInNgIf { +class LinkInNgIf { alwaysTrue = true; } @@ -3550,7 +3538,7 @@ function createRoot(router: Router, type: any): ComponentFixture { QueryParamsAndFragmentCmp, StringLinkButtonCmp, WrapperCmp, - OutletInNgIf, + LinkInNgIf, ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, @@ -3576,7 +3564,7 @@ function createRoot(router: Router, type: any): ComponentFixture { QueryParamsAndFragmentCmp, StringLinkButtonCmp, WrapperCmp, - OutletInNgIf, + LinkInNgIf, ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, @@ -3604,7 +3592,7 @@ function createRoot(router: Router, type: any): ComponentFixture { QueryParamsAndFragmentCmp, StringLinkButtonCmp, WrapperCmp, - OutletInNgIf, + LinkInNgIf, ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, diff --git a/packages/router/test/router.spec.ts b/packages/router/test/router.spec.ts index df51f65c4c..77b8984ee7 100644 --- a/packages/router/test/router.spec.ts +++ b/packages/router/test/router.spec.ts @@ -11,7 +11,7 @@ import {TestBed, inject} from '@angular/core/testing'; import {ResolveData} from '../src/config'; import {PreActivation, Router} from '../src/router'; -import {ChildrenOutletContexts} from '../src/router_outlet_context'; +import {RouterOutletMap} from '../src/router_outlet_map'; import {ActivatedRouteSnapshot, RouterStateSnapshot, createEmptyStateSnapshot} from '../src/router_state'; import {DefaultUrlSerializer} from '../src/url_tree'; import {TreeNode} from '../src/utils/tree'; @@ -109,7 +109,7 @@ describe('Router', () => { function checkResolveData( future: RouterStateSnapshot, curr: RouterStateSnapshot, injector: any, check: any): void { const p = new PreActivation(future, curr, injector); - p.traverse(new ChildrenOutletContexts()); + p.traverse(new RouterOutletMap()); p.resolveData().subscribe(check, (e) => { throw e; }); } diff --git a/packages/router/testing/src/router_testing_module.ts b/packages/router/testing/src/router_testing_module.ts index 650502d11c..11fb8bb5fa 100644 --- a/packages/router/testing/src/router_testing_module.ts +++ b/packages/router/testing/src/router_testing_module.ts @@ -9,7 +9,7 @@ import {Location, LocationStrategy} from '@angular/common'; import {MockLocationStrategy, SpyLocation} from '@angular/common/testing'; import {Compiler, Injectable, Injector, ModuleWithProviders, NgModule, NgModuleFactory, NgModuleFactoryLoader, Optional} from '@angular/core'; -import {ChildrenOutletContexts, NoPreloading, PreloadingStrategy, ROUTES, Route, Router, RouterModule, Routes, UrlHandlingStrategy, UrlSerializer, provideRoutes, ɵROUTER_PROVIDERS as ROUTER_PROVIDERS, ɵflatten as flatten} from '@angular/router'; +import {NoPreloading, PreloadingStrategy, ROUTES, Route, Router, RouterModule, RouterOutletMap, Routes, UrlHandlingStrategy, UrlSerializer, provideRoutes, ɵROUTER_PROVIDERS as ROUTER_PROVIDERS, ɵflatten as flatten} from '@angular/router'; @@ -82,11 +82,11 @@ export class SpyNgModuleFactoryLoader implements NgModuleFactoryLoader { * @stable */ export function setupTestingRouter( - urlSerializer: UrlSerializer, contexts: ChildrenOutletContexts, location: Location, + urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, loader: NgModuleFactoryLoader, compiler: Compiler, injector: Injector, routes: Route[][], urlHandlingStrategy?: UrlHandlingStrategy) { const router = new Router( - null !, urlSerializer, contexts, location, injector, loader, compiler, flatten(routes)); + null !, urlSerializer, outletMap, location, injector, loader, compiler, flatten(routes)); if (urlHandlingStrategy) { router.urlHandlingStrategy = urlHandlingStrategy; } @@ -127,8 +127,8 @@ export function setupTestingRouter( provide: Router, useFactory: setupTestingRouter, deps: [ - UrlSerializer, ChildrenOutletContexts, Location, NgModuleFactoryLoader, Compiler, Injector, - ROUTES, [UrlHandlingStrategy, new Optional()] + UrlSerializer, RouterOutletMap, Location, NgModuleFactoryLoader, Compiler, Injector, ROUTES, + [UrlHandlingStrategy, new Optional()] ] }, {provide: PreloadingStrategy, useExisting: NoPreloading}, provideRoutes([]) diff --git a/tools/public_api_guard/router/router.d.ts b/tools/public_api_guard/router/router.d.ts index 8afd9e4318..27008b53d3 100644 --- a/tools/public_api_guard/router/router.d.ts +++ b/tools/public_api_guard/router/router.d.ts @@ -59,16 +59,6 @@ export interface CanLoad { canLoad(route: Route): Observable | Promise | boolean; } -/** @stable */ -export declare class ChildrenOutletContexts { - getContext(childName: string): OutletContext | null; - getOrCreateContext(childName: string): OutletContext; - onChildOutletCreated(childName: string, outlet: RouterOutlet): void; - onChildOutletDestroyed(childName: string): void; - onOutletDeactivated(): Map; - onOutletReAttached(contexts: Map): void; -} - /** @stable */ export declare function convertToParamMap(params: Params): ParamMap; @@ -167,15 +157,6 @@ export declare class NoPreloading implements PreloadingStrategy { preload(route: Route, fn: () => Observable): Observable; } -/** @stable */ -export declare class OutletContext { - attachRef: ComponentRef | null; - children: ChildrenOutletContexts; - outlet: RouterOutlet | null; - resolver: ComponentFactoryResolver | null; - route: ActivatedRoute | null; -} - /** @stable */ export interface ParamMap { readonly keys: string[]; @@ -258,7 +239,7 @@ export declare class Router { readonly routerState: RouterState; readonly url: string; urlHandlingStrategy: UrlHandlingStrategy; - constructor(rootComponentType: Type | null, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes); + constructor(rootComponentType: Type | null, urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes); createUrlTree(commands: any[], {relativeTo, queryParams, fragment, preserveQueryParams, queryParamsHandling, preserveFragment}?: NavigationExtras): UrlTree; dispose(): void; initialNavigation(): void; @@ -348,7 +329,7 @@ export declare class RouterModule { } /** @stable */ -export declare class RouterOutlet implements OnDestroy, OnInit { +export declare class RouterOutlet implements OnDestroy { activateEvents: EventEmitter; readonly activatedRoute: ActivatedRoute; readonly component: Object; @@ -356,13 +337,20 @@ export declare class RouterOutlet implements OnDestroy, OnInit { readonly isActivated: boolean; /** @deprecated */ readonly locationFactoryResolver: ComponentFactoryResolver; /** @deprecated */ readonly locationInjector: Injector; - constructor(parentContexts: ChildrenOutletContexts, location: ViewContainerRef, resolver: ComponentFactoryResolver, name: string); - activateWith(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver | null): void; + outletMap: RouterOutletMap; + constructor(parentOutletMap: RouterOutletMap, location: ViewContainerRef, resolver: ComponentFactoryResolver, name: string); + /** @deprecated */ activate(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver, injector: Injector, providers: ResolvedReflectiveProvider[], outletMap: RouterOutletMap): void; + activateWith(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver | null, outletMap: RouterOutletMap): void; attach(ref: ComponentRef, activatedRoute: ActivatedRoute): void; deactivate(): void; detach(): ComponentRef; ngOnDestroy(): void; - ngOnInit(): void; +} + +/** @stable */ +export declare class RouterOutletMap { + registerOutlet(name: string, outlet: RouterOutlet): void; + removeOutlet(name: string): void; } /** @stable */