diff --git a/packages/angular/ssr/src/routes/ng-routes.ts b/packages/angular/ssr/src/routes/ng-routes.ts index e2454896f832..7c2db5275023 100644 --- a/packages/angular/ssr/src/routes/ng-routes.ts +++ b/packages/angular/ssr/src/routes/ng-routes.ts @@ -10,7 +10,9 @@ import { APP_BASE_HREF, PlatformLocation } from '@angular/common'; import { ApplicationRef, Compiler, + EnvironmentInjector, Injector, + createEnvironmentInjector, runInInjectionContext, ɵConsole, ɵENABLE_ROOT_COMPONENT_BOOTSTRAP, @@ -195,14 +197,22 @@ async function* handleRoute(options: { appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata); } + const routeInjector = route.providers + ? createEnvironmentInjector( + route.providers, + parentInjector.get(EnvironmentInjector), + `Route: ${route.path}`, + ) + : parentInjector; + const loadedChildRoutes = await loadChildrenHelper( route, compiler, - parentInjector, + routeInjector, ).toPromise(); if (loadedChildRoutes) { - const { routes: childRoutes, injector = parentInjector } = loadedChildRoutes; + const { routes: childRoutes, injector = routeInjector } = loadedChildRoutes; yield* traverseRoutesConfig({ ...options, routes: childRoutes, diff --git a/packages/angular/ssr/test/routes/ng-routes_spec.ts b/packages/angular/ssr/test/routes/ng-routes_spec.ts index 5599e22c1ea5..d9fae4bcfb41 100644 --- a/packages/angular/ssr/test/routes/ng-routes_spec.ts +++ b/packages/angular/ssr/test/routes/ng-routes_spec.ts @@ -11,8 +11,13 @@ import '@angular/compiler'; /* eslint-enable import/no-unassigned-import */ -import { Component } from '@angular/core'; -import { Routes, provideRouter, withEnabledBlockingInitialNavigation } from '@angular/router'; +import { Component, InjectionToken, Injector, inject } from '@angular/core'; +import { + Route, + Routes, + provideRouter, + withEnabledBlockingInitialNavigation, +} from '@angular/router'; import { extractRoutesAndCreateRouteTree } from '../../src/routes/ng-routes'; import { PrerenderFallback, RenderMode } from '../../src/routes/route-config'; import { setAngularAppTestingManifest } from '../testing-utils'; @@ -717,4 +722,36 @@ describe('extractRoutesAndCreateRouteTree', () => { { route: '/**', renderMode: RenderMode.Server }, ]); }); + + it(`should create and run route level injector when 'loadChildren' is used`, async () => { + const ChildRoutes = new InjectionToken('Child Routes'); + setAngularAppTestingManifest( + [ + { + path: '', + component: DummyComponent, + providers: [ + { + provide: ChildRoutes, + useValue: [ + { + path: 'home', + component: DummyComponent, + }, + ], + }, + ], + loadChildren: () => inject(ChildRoutes), + }, + ], + [{ path: '**', renderMode: RenderMode.Server }], + ); + + const { routeTree, errors } = await extractRoutesAndCreateRouteTree({ url }); + expect(errors).toHaveSize(0); + expect(routeTree.toObject()).toEqual([ + { route: '/', renderMode: RenderMode.Server }, + { route: '/home', renderMode: RenderMode.Server }, + ]); + }); });