Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between PROVIDER, INJECTOR and SERVICE in Angular 2-7?

Could anyone please explain to me the differences in simpler words. Any real-time example with or without code would also work.

like image 957
Kapil Raghuwanshi Avatar asked Jun 14 '18 09:06

Kapil Raghuwanshi


1 Answers

A service is a class in Angular which is registered with an Angular dependency injector. In the below example, StudentService class is a service.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class StudentService {
  constructor() { }
}

An Angular injector is responsible for creating service instances and injecting them into classes. Usually injectors work behind the scenes. Below code shows injector being explicitly created.

constructor(private injector: Injector) { }

The below code inject the service directly to the host component.

injector.get(Service)

Providers tell the injector how to create the service. Without a provider, the injector would not know that it is responsible for injecting the service nor be able to create the service. Usually, providers are mentioned in the module or component metadata. For example, if a component want to call the service 'FileWriter', the component should mention in the metadata, that this service should be created and injected by the injector.

providers: [FileWriter]
like image 81
Rakesh M R Avatar answered Oct 08 '22 22:10

Rakesh M R