When you write an application you have to take 3 steps in order to perform an injection:
1. Create the service class.
2. Declare the dependencies on the receiving component.
3. Configure the injection (register the injection with angular in NgModule
).
The service will be called injectable because it represents what the components will receive via the injection.
@Injectable()
export class MyService {
getData(): void {
console.log('Fetching data');
}
}
Now that you have the thing to be injected, the next step, would be to declare the dependencies you want to receive when angular creates the component.
One way of doing this in angular, is by declaring the injectables we want in our component’s constructor:
export class MyApp {
constructor(private myService: MyService) {}
}
When you declare the injection in the component constructor, angular will do some reflection to figure out what class to inject. In other words angular will see that we are looking for an object of type MyService in the constructor and check the dependency injection system for an appropriate injection.
The final step for using dependency injection is to connect the things our components want injected from the injectables. Which means, we need to tell angular which thing to inject when a component declares its dependencies.
We do this by adding MyService to the providers key of our NgModule
.
@NgModule({
declarations: [ MyApp ],
imports: [ BrowserModule ],
providers: [ MyService ]
})