为什么在注入服务后每次都调用构造函数? [英] Why is constructor call each time after injection of service?
本文介绍了为什么在注入服务后每次都调用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Angular2.我在节提供程序中使用单例服务 @NgModule({})
: ['MenuService']
我使用 MenuService
.
I use Angular 2. I use singleton service @NgModule({})
in section providers: ['MenuService']
I use MenuService
.
MenuService 如下:@Injectable()
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) {}
}
我见过两次 console.log('Called');
,为什么会重复调用它?
I see console.log('Called');
twice, why is it called repeatly?
推荐答案
服务在注入组件时将始终运行其构造函数,它必须设置服务的字段/属性.因此,这根本不是怪异的行为.注入的接口充当"两个对象.
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.
这篇关于为什么在注入服务后每次都调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文