B45i
B45i

Reputation: 2602

Injecting service to a specified module in angular 6+

When a new service is created using angular-cli, the service is injected at the root level using @Injectable decorator.

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

But I don't want the service at the root level, I want it only in a specified module. Before ng6, this can be achieved by adding he serves only to the providers array of the specified module. is this still the right way in ng6+

Upvotes: 2

Views: 2916

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21628

Services are injected into constructors of components, directives, services etc, they are provided at root, module or components levels. There is no concept of injecting a service at a module level. You can provide a service at a module level, what that means is the same instance of that service will be injected in all items of the module that request the service. If your service is only used in a single module then providing it at a root or module level makes no difference at all, the end result is that all requests for injection get the same instance.

It is fine to just provide all your services at the root level and not worry about where they used. The only time you need to provide a service other than in the root is when you want unique instances of the service at different places. Just say a component hierarchy shares data with a shared service and you don't want that data to be available outside of the components then you have the top most component provide the service and then all children of that component will get the same instance but another instance of the parent component will have it's own unique instance.

Providing components at a module level is not really necessary with the introduction of provided in root.

Upvotes: 4

Sajeetharan
Sajeetharan

Reputation: 222522

In order to inject a service in a specific module using the newer syntax you just do something like this:

import { Injectable } from "@angular/core";
import { YourModule } from "path/to/your.module";

@Injectable({
    providedIn: YourModule
})
export class SomeModuleScopedService {}

or you can do with the angular cli command,

ng g s services/testService --module=services/services.module

Upvotes: 2

Related Questions