Questions
What is dependency injection and how do you use it in Angular?
The Scenario
You are a frontend engineer at a social media company. You are building a new component that needs to get data from a service.
You could create a new instance of the service in the component, but this would not be a very good solution. It would make the component difficult to test, and it would not be very flexible.
The Challenge
Explain what dependency injection is in Angular and how you would use it to solve this problem. What are the key benefits of using dependency injection?
A junior engineer might not be aware of dependency injection. They might try to solve this problem by creating a new instance of the service in the component, which would be a very bad practice.
A senior engineer would know that dependency injection is the perfect tool for this job. They would be able to explain what dependency injection is and how to use it to provide a service to a component.
Step 1: Understand What Dependency Injection Is
Dependency injection (DI) is a design pattern in which a class requests dependencies from external sources rather than creating them itself.
Step 2: The Key Concepts of Dependency Injection
| Concept | Description |
|---|---|
| Injector | The injector is the main container for all the dependencies in an Angular application. |
| Provider | A provider is a recipe for creating a dependency. |
| Dependency | A dependency is an object that a class needs to perform its function. |
Step 3: Use Dependency Injection
Here’s how we can use dependency injection to provide a service to a component:
1. Create a service:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
get_data() {
return 'some data';
}
}2. Inject the service into a component:
import { Component } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'my-component',
template: '<h1>{{ myData }}</h1>'
})
export class MyComponent {
myData: string;
constructor(private myService: MyService) {
this.myData = this.myService.get_data();
}
}In this example, we use the constructor to inject the MyService into the MyComponent.
Practice Question
You want to provide a different implementation of a service for a specific component. Which of the following would you use?