What is the inject() function, and how does it compare with constructor injection?
Model answer
inject() gets a dependency from the current injection context, such as a field initialiser, a constructor, a factory or a functional guard: private http = inject(HttpClient). Constructor injection lists the dependencies as constructor parameters.
inject() is shorter, works in functions (route guards, interceptors) where there is no constructor, and plays well with class inheritance. Both give the same instance. It must be called in an injection context, not later inside a random method.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- What is a directive? What are the types?
- What is the difference between ngClass and ngStyle, and how do they compare with class and style bindings?
- What is a pipe? Name some built-in pipes.
- How do you create a custom pipe? What is the difference between pure and impure pipes?
- What does the async pipe do, and why is it recommended?
- How do you build a custom attribute directive?