Angular2中的Service并不是单例模式

2015年做了一个使用angularjs 1框架的项目,2016年伊始公司的项目转为使用Angular2框架。

在开发过程中发现了一个坑,这个坑就是在Angular JS 1.x中的Service是单例模式,只要创建了一个Service,那么程序都在使用这唯一的Service。

但是在Angular 2中,Service并不是单例模式,Compnent会从自己向母页寻找Service,直到Module。

如果不同的Component里面都在providers添加了Service,那么这些Component都只会访问自己的Service。

如果想在不同的Component中使用同一个Service,那就找到这两个Component的母页,在母页的providers中加入这个Service。