Performance: @Injectable decorator and providedIn
This concept affects the bundle size and initial load time by controlling service tree-shaking and injection scope.
@Injectable({ providedIn: 'root' })
export class DataService {}@Injectable() export class DataService {} @NgModule({ providers: [DataService] }) export class AppModule {}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Providing service in NgModule providers | 0 | 0 | 0 | [X] Bad |
| Using @Injectable({ providedIn: 'root' }) | 0 | 0 | 0 | [OK] Good |
@Injectable decorator in Angular?@Injectable@Injectable decorator tells Angular that the class can be used as a service and injected into other classes.@Component or @NgModule serve different purposes, not marking services.@Injectable = marks service [OK]@Injectable means service ready for injection [OK]@Injectable with @Component@Injectable?providedIn, not provideIn or others.'root' as the value means the service is available app-wide as a singleton.providedIn: 'root' is correct syntax [OK]providedIn with value 'root' [OK]providedIn as provideInprovidedAt or provideAt @Injectable({ providedIn: 'root' })
export class DataService {
constructor() { console.log('Service created'); }
}providedIn: 'root'providedIn: 'root' means singleton service [OK] @Injectable({
providedIn: root
})
export class LoggerService {}@Injectable is correct, constructor is optional, and providedIn is valid here.providedIn [OK]@Injectable and providedIn to achieve this?providedIn: 'root' makes the service app-wide singleton, so not limited to a feature module.providedIn: FeatureModule where FeatureModule is the NgModule class is possible but not officially recommended or supported in all Angular versions. The standard way is to omit providedIn and add the service to the feature module's providers array.providedIn: 'any' creates a new instance in each injector but does not restrict to a single module. Importing with providedIn: 'root' makes it app-wide.@Injectable() without providedIn and add the service to the feature module's providers array -> Option AprovidedIn and adding to providers array scopes service to module [OK]Pass the test and this pattern moves unknown