Dependency injection in Angular | Get services without creating there instance manually
Dependency: every code or module that is need of component is component dependancy because component need that.
we create instance of service to use that service but using dependncy injection we can use that service directly without creating its instance
that istance is provided by angular depency injection to components that need it.
Dependency Injection is a technique in which a class receives its dependencies from external sources rather than creating them itself.
1. create constructer and pass its parameter with service class name
2. in component decurator add that service using providers
3. use that instance using this.variablename
home.component.ts
import { Component } from '@angular/core';
import { EnrollService } from '../Services/enroll.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers:[EnrollService]
})
export class HomeComponent {
constructor(private enrollService:EnrollService){
}
title="Home View";
OnEnroll(){
this.enrollService.onEnrollClick(this.title);
}
}
home.component.html
<button (click)="OnEnroll()">home works!</button>
app/Services/enroll.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EnrollService {
constructor() { }
onEnrollClick(title:string){
alert("Thanks for enroll in "+title);
}
}