1

Suppose you have an Angular service (ZombieService) which, for example, monitors an other service. And, ZombieService isn't injected anywhere DEMO

The problem is that, when you do not inject a service anywhere, that service is completely ignored (not executed). The solution is to inject it into, for example, AppComponent

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.scss' ]
})
export class AppComponent  {
    constructor(zombieService: ZombieService) {}
    ...
}

Although this works, I was wondering if there isn't a better solution for this. Any suggestions?

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

1 Answers1

2

The problem is that, when you do not inject a service anywhere, that service is completely ignored (not executed).

Because a file which is not referred by any others, is as good as a file from different project. There is no point in initialising a service which has no reference.

Only the files referred from main entry file(s) are considered for creating bundling by WebPack or any other JS orchestrating tool.

These kinds of services are injected at AppComponent, or can also be at module-level component.

This is the most general case of tracking / analytics, and there's an initialisation step which needs to be done in service for most of them, which needs the service to be injected at some component (probably AppComponent).

Prajwal
  • 3,930
  • 5
  • 24
  • 50