0

I use Angular 2. I use singleton service @NgModule({}) in section providers: ['MenuService'] I use MenuService.

MenuService looks as: @Injectable()

export class MenuService {

  constructor(private userService: UserService, private i18nService: I18nService) { console.log('Called'); }
}

There are two components where I inject this service:

export class HeaderComponent {
  constructor(private menuService: MenuService) {}
}

export class HomeComponent {
  constructor(private menuService: MenuService) {}
}

I see console.log('Called'); twice, why is it called repeatly?

POV
  • 11,293
  • 34
  • 107
  • 201

3 Answers3

1

There are two ways to make a service a singleton in Angular:

  • Declare that the service should be provided in the application root.

  • Include the service in the AppModule or in a module that is only imported by the AppModule.

Beginning with Angular 6.0, the preferred way to create a singleton services is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

taken from Angular official documentation.

Anuradha Gunasekara
  • 6,553
  • 2
  • 27
  • 37
1

Yes, injected service constructors are called by component immediately when they are initialized.

export class HomeComponent {
  constructor(private menuService: MenuService) {}
}

is equivalent of doing

private menuService: MenuService;
export class HomeComponent {
  constructor() {
      this.menuService = new MenuService(params...);
  }
}

So basically, DI eliminates the need of creating the objects explicitly as shown in second method.

DI is helpful when MenuService constructor is expecting some parameters and you are not sure what to send.

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
-2

A service will always run its constructor when injected in a component, it has to set the fields/props of the service. So it is not weird behaviour at all. The injected interfaces 'act' as 2 objects.

JohnMcClane
  • 128
  • 6