Angular restrict service to only one component tree

3.1k Views Asked by At

i want to implement a service and let it provide to only one named component or module and not to any other component or module.

So whenever anyone tries to provide that service to another component they get an error and the program should not compile.

Is there any way to do that?

Thanks in advance.

EDIT:

I guess you misunderstood my question. I am saying that no developer shall be able to add that service to any where in providers array except one component tree.

2

There are 2 best solutions below

2
On

If you provide it to a component it will only be available to that component and its children:

@Component({
  selector: "component",
  providers: [Service]
})

See: https://angular.io/guide/providers#limiting-provider-scope-with-components.

A way to limit scope to a module or component:

@Injectable({ providedIn: HelloComponent })
export class Service {}

So if this component itself has no children, it is in fact the only named component that has access to it. Other components will receive an Injector Error

0
On

Try this: Provide the service as a class in a component, it must create one instance for that component, and you can remove the provider from the module.

@Component({
  selector: "component",
  providers: [{ provide: Service, useClass: Service }]
})

and null injectable, the injectable is not provided in any scope automatically...

@Injectable()
export class Service {}