Angular中@Injectable.providedIn与NgModule.providers对比:教程方法有何优势?
providedIn: 'root' for Angular Services Great question! Moving from declaring services in @NgModule.providers to using @Injectable({ providedIn: 'root' }) is a recommended practice in Angular, and it brings several tangible benefits:
Tree-shaking optimization
This is hands down the biggest win. When you useprovidedIn: 'root', Angular marks the service as tree-shakable. If your service isn't actually used anywhere in your application, bundlers like Webpack can eliminate it from the final production bundle entirely. In contrast, adding a service to@NgModule.providersmeans it gets included in the bundle regardless of whether it's used—wasting valuable bundle size.Simpler, less error-prone setup
You no longer need to manually add the service to every module that needs it (or remember to add it to the root module for app-wide access). The service's provision is defined directly in its own class, so you avoid duplicate declarations, missing entries, or accidental multiple instances from adding the service to multiple modules.Built-in singleton behavior (with flexible scoping)
By default,providedIn: 'root'registers the service with the root injector, ensuring a single instance exists across your entire app. If you need a service to be scoped to a specific module (instead of app-wide), you can even target that module directly:@Injectable({ providedIn: SomeFeatureModule }) export class FeatureSpecificService { ... }This gives you precise control over the service's scope without cluttering module providers.
Improved code organization
The service's availability and scope are documented right in its own definition. Anyone looking at the service class can immediately understand where it's provided, instead of having to dig through module files to find its entry in theprovidersarray. This makes your codebase easier to navigate and maintain.Better lazy-loading integration
When a service is only used by components in a lazy-loaded module, Angular automatically bundles the service with that lazy module's chunk instead of the main app bundle. This reduces the initial load time of your application. If you had declared the service in the root module's providers, it would be loaded upfront even if the lazy module is never accessed.
内容的提问来源于stack exchange,提问作者yuval.bl

