本文介绍了为什么每次注入服务后都会调用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Angular 2.我在部分提供程序中使用单例服务 @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?
推荐答案
服务在注入组件时将始终运行其构造函数,它必须设置服务的字段/道具.所以这根本不是奇怪的行为.注入的接口充当"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.
这篇关于为什么每次注入服务后都会调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!