angularangular-di

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


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"?


Solution

  • 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.