kittencup / angular2-ama-cn

angular2 随便问
691 stars 101 forks source link

@Inject(ShopService) 获取到的实例感觉不是单例的 #148

Open greper opened 8 years ago

greper commented 8 years ago

我在两个页面中使用 @Inject(ShopService) 注入到constructor里面

shopService有一个init方法 init(){ if(this.inited){ return; } console.log("shopService初始化"); this.inited =true; }

每个页面都调用这个init方法

结果每次都打印出shopService初始化

@Inject注入进来的service到底是不是单例的? 或者说注入进来的service无法保存自有状态?

kittencup commented 8 years ago

必须配置他们共同的父组件 provider:ShopService ,每个独立组件不需要再配置provider

hstarorg commented 8 years ago

如果在组件中配置了providers属性,那么该Service就会在组件中创建一份新的实例。如果想实现单例,那么可以在根组件中配置providers,然后其他所有组件,都只需要注入。