'Second service's constructor method not getting called

I have an Angular app where in my module I have injected two singleton services as shown below:

@NgModule({
    imports: [],
    exports : [],
    declarations: [ MyComponent ],
    providers: [ ImageService, DashboardService ]
})

And in both of these services I have the constructors defined. But only the code written in first constructor is getting executed on login. But the code written in the second constructor is not getting executed.

But if I refresh the page both constructors are called. Not sure why it is happening. Any help is appreciated.



Solution 1:[1]

Instances of services are created at the point that are needed (for performance purposes). When a Component (or another service) require a Service, angular traverses the Dependency Injection tree, in look for a definition (and an instance of a service).

Most probably, the constructor that is being executed is of the service that is required by your component, while the one that is not being executed, is not being required by component.

Let's take the following examples

Case 1

@Component({...})
export class MyComponent {
    constructor(private imageService:ImageService) {}
}

The above will create an instance of ImageService only.

Case 2

@Component({...})
export class MyComponent {
    constructor(private dashboardService:DashboardService) {}
}

This will create an instance of DashboardService only.

Case 3

@Component({...})
export class MyComponent {
    constructor(private imageService:ImageService, private dashboardService:DashboardService) {}
}

This will create an instance of both the ImageService and the DashboardService.

You can read further on dependency injection on the Angular site, in the dependency injection section, more specifically Angular Dependency Injection and Hierarchical Injectors.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JeanPaul A.