TheGreatZab
TheGreatZab

Reputation: 163

Difference Between Service in the Constructor Versus Listed as a Provider in a Component?

What would be the difference if in a component I declare a service as:

A provider:

@Component({
  ...
  providers: [MyService]})

Versus in the constructor:

constructor(private myService: MyService) {
    ...
}

Is there a preferred method?

Upvotes: 0

Views: 462

Answers (1)

Mohammad
Mohammad

Reputation: 971

When you register a provider at the component level, you get a new instance of the service with each new instance of that component.

When you provide the service at the root level, Angular creates a single, shared instance of MyService and injects it into any class that asks for it.

Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled app if it isn't used.

@Injectable({ providedIn: 'root' })

Upvotes: 2

Related Questions