Why is constructor call each time after injection of service?

≡放荡痞女 提交于 2021-02-08 09:52:46

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/51395830/why-is-constructor-call-each-time-after-injection-of-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!