reusable common functionality/data across multiple components
//sample.service.ts
@injectable
export class SampleService{
public getSomething() { return "Hello world"; }
}
How to Invoke a service without dependency injection:
//app.component.ts
@Component({ selector: 'app-root', templateUrl: './app.component.html'})
export class AppComponent
{
sampleService:SampleService;
constructor(){
this.sampleService = new SampleService();}
}
way of providing dependencies to classes , without creating them internally.
Note: it follows singleton pattern
//app.component.ts
@Component({ selector: 'app-root', templateUrl: './app.component.html', providers: [SampleService]})
export class AppComponent
{
constructor(public sampleService:SampleService){ }
}
@Injectable({
providedIn: 'root',
})export class SampleService{}
providers :[{ provide: ProductService, useClass: fakeProductService }]
constructor(private productService: ProductService) { }
providers :[{ provide: 'API_URL', useValue: 'https://example.com/api' }]
constructor(@Inject('API_URL') private apiUrl: string) { }
{ provide: MyService, useFactory: myServiceFactory, deps: [DepService] }
function myServiceFactory(depService: DepService) {
return new MyService(depService);
}
{ provide: NewService, useClass: ExistingService },
{ provide: ExistingService, useExisting: NewService }