0 什么是依赖
如果在class A中使用了class B,就说A依赖B。
1 为什么要依赖注入
类与类之间的紧耦合不利于测试、debug等。
2 什么时候需要依赖注入
2.1 Singleton
当整个应用需要共享一个单例
2.2 environment-specific variables
需要配置对整个环境都起作用的常量(类似全局变量)
2.3 Call any function and inject the return value of that function
3 Angular怎么依赖注入
3.1 涉及的概念
provider
injector
dependency
3.2 具体的流程
3.2.1 使用 ReflectiveInjector.resolveAndCreate([serviceName...])
例如需要创建单例时,我们可以把单例提供的功能放到单独的service文件夹下,然后用@injectable修饰。在需要用这个服务的类中,使用ReflectiveInjector.resolveAndCreate([serviceName...])获得injector,再通过injector.get(serviceName)来获取这个服务。
3.2.2 更方便的做法
也是Angular中的常见做法。在@N