M's*_*ph' 8 dependency-injection angular
我已经使用 Angular2/4 几个月了,但我仍然无法弄清楚这两种方法之间有什么区别,以及关于依赖注入我应该使用哪一种
你能帮我吗。
...
constructor(
private myService: MyService
) {
// this.myService.myMethod() ...
}
...
Run Code Online (Sandbox Code Playgroud)
和
...
private myService: MyService;
constructor(
injector: Injector
) {
this.myService = injector.get(MyService);
// this.myService.myMethod() ...
}
...
Run Code Online (Sandbox Code Playgroud)
我了解每种方法的作用,但我无法找出最佳实践。
我知道这可能是主观意见,但我认为两者都有优点和缺点。
感谢您的任何解释。
您应该始终选择第一个选项:
...
constructor(
private myService: MyService
) {
// this.myService.myMethod() ...
}
...
Run Code Online (Sandbox Code Playgroud)
第二种方法有效,因为当您注入时,MyService它是使用Injector.
AngularInjector允许注入,因为您在动态实例化模块或组件时可能需要使用它:
成分:
export class ModuleLoaderComponent {
constructor(private _injector: Injector,private loader: NgModuleFactoryLoader) { ... }
ngAfterViewInit() {
this.loader.load('app/t.module#TModule').then((factory) => {
const module = factory.create(this._injector); <-----------------
Run Code Online (Sandbox Code Playgroud)
模块:
export class RouterConfigLoader {
load(parentInjector, route) {
...
const modFactory = this.loadModuleFactory(route.loadChildren);
const module = modFactory.create(parentInjector);
}
Run Code Online (Sandbox Code Playgroud)
您可以在以下文章中阅读有关动态实例化的更多信息:
正如 @estus 指出的,injector也用于在构造函数中注入依赖项导致循环依赖项或您希望根据某些条件获取依赖项的情况。