forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinject-async.service.ts
More file actions
92 lines (80 loc) · 2.41 KB
/
inject-async.service.ts
File metadata and controls
92 lines (80 loc) · 2.41 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
/*!
* @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 {
DestroyRef,
ENVIRONMENT_INITIALIZER,
EnvironmentInjector,
Injectable,
Injector,
Provider,
ProviderToken,
Type,
createEnvironmentInjector,
inject,
} from '@angular/core';
/**
* Convience method for lazy loading an injection token.
*/
export async function injectAsync<T>(
injector: Injector,
providerLoader: () => Promise<ProviderToken<T>>,
): Promise<T> {
const injectImpl = injector.get(InjectAsyncImpl);
return injectImpl.get(injector, providerLoader);
}
@Injectable({providedIn: 'root'})
class InjectAsyncImpl<T> {
private overrides = new WeakMap(); // no need to cleanup
override<T>(type: Type<T>, mock: Type<unknown>) {
this.overrides.set(type, mock);
}
async get(injector: Injector, providerLoader: () => Promise<ProviderToken<T>>): Promise<T> {
const type = await providerLoader();
// Check if we have overrides, O(1), low overhead
if (this.overrides.has(type)) {
const override = this.overrides.get(type);
return new override();
}
if (!(injector instanceof EnvironmentInjector)) {
// this is the DestroyRef of the component
const destroyRef = injector.get(DestroyRef);
// This is the parent injector of the injector we're creating
const environmentInjector = injector.get(EnvironmentInjector);
// Creating an environment injector to destroy it afterwards
const newInjector = createEnvironmentInjector([type as Provider], environmentInjector);
// Destroy the injector to trigger DestroyRef.onDestroy on our service
destroyRef.onDestroy(() => {
newInjector.destroy();
});
// We want to create the new instance of our service with our new injector
injector = newInjector;
}
return injector.get(type)!;
}
}
/**
* Helper function to mock the lazy loaded module in `injectAsync`
*
* @usage
* TestBed.configureTestingModule({
* providers: [
* mockAsyncProvider(SandboxService, fakeSandboxService)
* ]
* });
*/
export function mockAsyncProvider<T>(type: Type<T>, mock: Type<unknown>) {
return [
{
provide: ENVIRONMENT_INITIALIZER,
multi: true,
useValue: () => {
inject(InjectAsyncImpl).override(type, mock);
},
},
];
}