You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: adev/src/content/guide/di/dependency-injection-context.md
+31-6Lines changed: 31 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -5,11 +5,11 @@ This means that injectors can only work when code is executed in such a context.
5
5
6
6
The injection context is available in these situations:
7
7
8
-
* During construction (via the `constructor`) of a class being instantiated by the DI system, such as an `@Injectable` or `@Component`.
9
-
* In the initializer for fields of such classes.
10
-
* In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`.
11
-
* In the `factory` function specified for an `InjectionToken`.
12
-
* Within a stack frame that runs in an injection context.
8
+
- During construction (via the `constructor`) of a class being instantiated by the DI system, such as an `@Injectable` or `@Component`.
9
+
- In the initializer for fields of such classes.
10
+
- In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`.
11
+
- In the `factory` function specified for an `InjectionToken`.
12
+
- Within a stack frame that runs in an injection context.
13
13
14
14
Knowing when you are in an injection context will allow you to use the [`inject`](api/core/inject) function to inject instances.
15
15
@@ -66,7 +66,32 @@ Note that `inject` will return an instance only if the injector can resolve the
66
66
67
67
## Asserts the context
68
68
69
-
Angular provides the `assertInInjectionContext` helper function to assert that the current context is an injection context.
69
+
Angular provides the `assertInInjectionContext` helper function to assert that the current context is an injection context and throws a clear error if not. Pass a reference to the calling function so the error message points to the correct API entry point. This produces a clearer, more actionable message than the default generic injection error.
You can then call this helper **from an injection context** (constructor, field initializer, provider factory, or code executed via `runInInjectionContext`):
0 commit comments