8

I've read the docs thoroughly and, although I can't find exactly where it's referenced, I have the impression that declaring a service in an eagerly loaded module's providers array will make the singleton available to the application scope. If this is true,

Is using @Injectable providedIn for any non-lazy-loaded module the same as providedIn: "root"?

papiro
  • 2,158
  • 1
  • 20
  • 29

1 Answers1

7

Yes it is the same.

In general, you should always just use the providedIn: "root" syntax in the @Injectable declaration. It even works with lazy loading when its just loaded in one module, so the service wont be loaded until angular loads the module. Its a way better construct.

I think the only 2 exceptions to prefering providedIn are 1) You want to declare it in a component. This will cause it to not be a singleton, but scoped to the component 2) You are using it in 2 separate, but both lazy loaded modules (and its also not used in the initial load), in this case I believe the best choices is eagerly load it by bringing it into the AppModule on initial load.

bgraham
  • 1,939
  • 1
  • 10
  • 17
  • sadly there is this reason to https://github.com/angular/angular/issues/25784#issuecomment-532055631 This doesn't always allow the developer to use injectable instead of providers – Giacomo Cerquone Apr 23 '20 at 16:10