In a simple term we can say dependency injection in angular are created once at the time of initialisation of service or component then throughout the application we can reuse same object without re-initialisation.
So, this is clear now advantage of dependency injection is to not creating the object in each component and maintain the state of service.
Creating a injectable service:
ng generate service test
it will create a service named test
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class TestService {
constructor() { }
}
In the above code @Injectable is a decorator which specifies that Angular can use this class in the DI system.
We can pass multiple metadata in decorator to describe the functionality of component, here we have defined providedIn which means this service can be used in any component.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class TestService {
myTests=[{id:1,name:"test1"}]
constructor(private logger: Logger) { }
getAllTest() {
return this.myTests;
}
}
We created a function getAllTest and we can use it in our component or other services.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test-service,
templateUrl: './test-service.component.html',
styleUrls: ['./test-service.component.css']
})
export class TestServiceComponent implements OnInit {
constructor(testService: TestService){
testService.getAllTest();
}
}
Hope this make your all doubts clear and you can comment if require any discussion.