What is a provider (Provider)?
Provider is an instruction for Angular on how to create or where to get a dependency when it is requested through DI.
In simple terms: a provider is a rule that tells the injector:
"If someone asks for this service, give them this object."
Example:
ts
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class UserService {}Here providedIn: 'root' is the provider.
It tells Angular: create a single instance of UserService in the root injector.
A provider can also be set manually:
ts
providers: [
{ provide: UserService, useClass: UserService }
]or, for example:
ts
providers: [
{ provide: 'API_URL', useValue: 'https://api.example.com' }
]What a provider does:
- specifies which token (key) to use (
UserService,'API_URL', and so on); - explains what to return (
useClass,useValue,useExisting,useFactory); - states where to register it, in a module, a component, or at the application level.
Summary: A provider is a way to tell Angular exactly how to create or supply a dependency when it is needed.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.