Repository navigation
Expand file tree
/
Copy pathrouter_config_loader.ts
More file actions
187 lines (173 loc) · 6.67 KB
/
Copy pathrouter_config_loader.ts
File metadata and controls
187 lines (173 loc) · 6.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/**
* @license
* Copyright Google LLC 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.dev/license
*/
import {
Compiler,
EnvironmentInjector,
inject,
InjectionToken,
Injector,
ɵmaybeUnwrapDefaultExport as maybeUnwrapDefaultExport,
NgModuleFactory,
ɵresolveComponentResources as resolveComponentResources,
runInInjectionContext,
Service,
Type,
} from '@angular/core';
import {standardizeConfig} from './components/empty_outlet';
import {LoadedRouterConfig, Route, Routes} from './models';
import {wrapIntoPromise} from './utils/collection';
import {assertStandalone, validateConfig} from './utils/config';
/**
* The DI token for a router configuration.
*
* `ROUTES` is a low level API for router configuration via dependency injection.
*
* We recommend that in almost all cases to use higher level APIs such as `RouterModule.forRoot()`,
* `provideRouter`, or `Router.resetConfig()`.
*
* @publicApi
*/
export const ROUTES = new InjectionToken<Route[][]>(
typeof ngDevMode !== 'undefined' && ngDevMode ? 'ROUTES' : '',
);
@Service()
export class RouterConfigLoader {
private componentLoaders = new WeakMap<Route, Promise<Type<unknown>>>();
private childrenLoaders = new WeakMap<Route, Promise<LoadedRouterConfig>>();
onLoadStartListener?: (r: Route) => void;
onLoadEndListener?: (r: Route) => void;
private readonly compiler = inject(Compiler);
// TODO(v23): Run loadComponent and loadChildren in root environment injector in 3p as well.
// g3-only private readonly environmentInjector = inject(EnvironmentInjector);
// TODO(v23): Remove unused `injector` parameter once `loadComponent` uses `this.environmentInjector` in 3p.
async loadComponent(injector: EnvironmentInjector, route: Route): Promise<Type<unknown>> {
if (this.componentLoaders.get(route)) {
return this.componentLoaders.get(route)!;
} else if (route._loadedComponent) {
return Promise.resolve(route._loadedComponent);
}
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
const loader = (async () => {
try {
const loaded = await wrapIntoPromise(
// g3-only runInInjectionContext(this.environmentInjector, () => route.loadComponent!()),
runInInjectionContext(injector, () => route.loadComponent!()), // 3p-only
);
const component = await maybeResolveResources(maybeUnwrapDefaultExport(loaded));
if (this.onLoadEndListener) {
this.onLoadEndListener(route);
}
(typeof ngDevMode === 'undefined' || ngDevMode) &&
assertStandalone(route.path ?? '', component);
route._loadedComponent = component;
return component;
} finally {
this.componentLoaders.delete(route);
}
})();
this.componentLoaders.set(route, loader);
return loader;
}
loadChildren(parentInjector: Injector, route: Route): Promise<LoadedRouterConfig> {
if (this.childrenLoaders.get(route)) {
return this.childrenLoaders.get(route)!;
} else if (route._loadedRoutes) {
return Promise.resolve({routes: route._loadedRoutes, injector: route._loadedInjector});
}
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
const loader = (async () => {
try {
const result = await loadChildren(
route,
this.compiler,
parentInjector,
this.onLoadEndListener,
// g3-only this.environmentInjector,
);
route._loadedRoutes = result.routes;
route._loadedInjector = result.injector;
route._loadedNgModuleFactory = result.factory;
return result;
} finally {
this.childrenLoaders.delete(route);
}
})();
this.childrenLoaders.set(route, loader);
return loader;
}
}
/**
* Executes a `route.loadChildren` callback and converts the result to an array of child routes and
* an injector if that callback returned a module.
*
* This function is used for the route discovery during prerendering
* in @angular-devkit/build-angular. If there are any updates to the contract here, it will require
* an update to the extractor.
*/
export async function loadChildren(
route: Route,
compiler: Compiler,
parentInjector: Injector,
onLoadEndListener?: (r: Route) => void,
// TODO(v23): Update `@angular/build` route extractor to pass `environmentInjector` and make it required.
// g3-only environmentInjector?: EnvironmentInjector,
): Promise<LoadedRouterConfig> {
const loaded = await wrapIntoPromise(
// g3-only runInInjectionContext(environmentInjector ?? parentInjector, () => route.loadChildren!()),
runInInjectionContext(parentInjector, () => route.loadChildren!()), // 3p-only
);
const t = await maybeResolveResources(maybeUnwrapDefaultExport(loaded));
let factoryOrRoutes: NgModuleFactory<any> | Routes;
if (t instanceof NgModuleFactory || Array.isArray(t)) {
factoryOrRoutes = t;
} else {
factoryOrRoutes = await compiler.compileModuleAsync(t);
}
if (onLoadEndListener) {
onLoadEndListener(route);
}
// This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is
// no injector associated with lazy loading a `Route` array.
let injector: EnvironmentInjector | undefined;
let rawRoutes: Route[];
let requireStandaloneComponents = false;
let factory: NgModuleFactory<unknown> | undefined = undefined;
if (Array.isArray(factoryOrRoutes)) {
rawRoutes = factoryOrRoutes;
requireStandaloneComponents = true;
} else {
injector = factoryOrRoutes.create(parentInjector).injector;
factory = factoryOrRoutes;
// When loading a module that doesn't provide `RouterModule.forChild()` preloader
// will get stuck in an infinite loop. The child module's Injector will look to
// its parent `Injector` when it doesn't find any ROUTES so it will return routes
// for it's parent module instead.
rawRoutes = injector.get(ROUTES, [], {optional: true, self: true}).flat();
}
const routes = rawRoutes.map(standardizeConfig);
(typeof ngDevMode === 'undefined' || ngDevMode) &&
validateConfig(routes, route.path, requireStandaloneComponents);
return {routes, injector, factory};
}
async function maybeResolveResources<T>(value: T): Promise<T> {
// In JIT mode we usually resolve the resources of components on bootstrap, however
// that won't have happened for lazy-loaded. Attempt to load any pending
// resources again here.
if ((typeof ngJitMode === 'undefined' || ngJitMode) && typeof fetch === 'function') {
try {
await resolveComponentResources(fetch);
} catch (error) {
console.error(error);
}
}
return value;
}