为什么注入服务后每次都调用构造函数?
Why is constructor call each time after injection of service?
我使用Angular 2.我在section providers中使用单例服务@NgModule({})
:['MenuService']
我使用MenuService
.
MenuService 看起来像:
@Injectable()
export class MenuService {
constructor(private userService: UserService, private i18nService: I18nService) { console.log('Called'); }
}
我在其中注入了两个组件:
export class HeaderComponent {
constructor(private menuService: MenuService) {}
}
export class HomeComponent {
constructor(private menuService: MenuService) {}
}
我看到console.log('Called');
两次,为什么重复调用?
服务总是运行它的构造函数,当注入一个组件时,它必须设置服务的fields/props。所以这根本不是奇怪的行为。注入接口 'act' 作为 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 {
}
是的,注入的服务 constructors
在初始化时被组件立即调用。
export class HomeComponent {
constructor(private menuService: MenuService) {}
}
相当于做
private menuService: MenuService;
export class HomeComponent {
constructor() {
this.menuService = new MenuService(params...);
}
}
所以基本上,DI
消除了显式创建对象的需要,如第二种方法所示。
DI
在 MenuService
构造函数需要一些参数而您不确定要发送什么时很有用。
我使用Angular 2.我在section providers中使用单例服务@NgModule({})
:['MenuService']
我使用MenuService
.
MenuService 看起来像: @Injectable()
export class MenuService {
constructor(private userService: UserService, private i18nService: I18nService) { console.log('Called'); }
}
我在其中注入了两个组件:
export class HeaderComponent {
constructor(private menuService: MenuService) {}
}
export class HomeComponent {
constructor(private menuService: MenuService) {}
}
我看到console.log('Called');
两次,为什么重复调用?
服务总是运行它的构造函数,当注入一个组件时,它必须设置服务的fields/props。所以这根本不是奇怪的行为。注入接口 'act' 作为 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
decoratorimport { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class UserService { }
是的,注入的服务 constructors
在初始化时被组件立即调用。
export class HomeComponent {
constructor(private menuService: MenuService) {}
}
相当于做
private menuService: MenuService;
export class HomeComponent {
constructor() {
this.menuService = new MenuService(params...);
}
}
所以基本上,DI
消除了显式创建对象的需要,如第二种方法所示。
DI
在 MenuService
构造函数需要一些参数而您不确定要发送什么时很有用。