Could anyone please explain to me the differences in simpler words. Any real-time example with or without code would also work.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With