Angular 何时使用ng2 Injector.resolveAndCreate vs TypeScript构造函数

Angular 何时使用ng2 Injector.resolveAndCreate vs TypeScript构造函数,angular,dependency-injection,Angular,Dependency Injection,我在Angular 2中阅读并观看了这些关于依赖注入的视频: 并且在角度上非常了解DI。但我对如何正确使用它感到困惑 我的问题是什么时候使用类型定义(1),如下所示: import { Component } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'example-component', template: '<div>I am

我在Angular 2中阅读并观看了这些关于依赖注入的视频:

并且在角度上非常了解DI。但我对如何正确使用它感到困惑

我的问题是什么时候使用类型定义(1),如下所示:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
    selector: 'example-component',
    template: '<div>I am a component</div>'
})
class ExampleComponent {
    constructor(private http: Http) {}
}
import { Injector, provide } from 'angular2/core'
var injector = Injector.resolveAndCreate(
[
provide(SomeObj, {useClass: SomeObj})
]);
import { HttpClient } from '@angular/common/http';
const customInjector = new StaticInjector([
    {provide: `MyCustomToken`, useValue: 'just a string value', deps: [HttpClient]}
])

第二个问题让我感到困惑,因为我不确定它应该放在哪里(组件、服务或其他?),如何使用它?

首先要注意的是,在
ReflectiveInjector
上调用
resolveAndCreate
方法(不是
Injector
):

第二件事是
ReflectiveInjector
被弃用,取而代之的是
StaticInjector
。阅读更多关于它的文章

因此,现在如果要创建自定义喷油器,您应该使用
StaticInjector
可以执行以下操作:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
    selector: 'example-component',
    template: '<div>I am a component</div>'
})
class ExampleComponent {
    constructor(private http: Http) {}
}
import { Injector, provide } from 'angular2/core'
var injector = Injector.resolveAndCreate(
[
provide(SomeObj, {useClass: SomeObj})
]);
import { HttpClient } from '@angular/common/http';
const customInjector = new StaticInjector([
    {provide: `MyCustomToken`, useValue: 'just a string value', deps: [HttpClient]}
])
第二个让我困惑,因为我不知道它应该放在哪里 去

使用反射式或静态注入器创建的自定义注入器可以在实例化时传递给模块或组件工厂。以下是文章中的一些示例:


对于(2),我是否应该通过声明所有类来创建自定义注入器,并使用
constcustominjector=newstaticinjector([…])在一个文件中,例如:
DIProvider.ts
,然后在需要时使用它,例如:
var someObj=customInjector.get(someObj)
像这样?@hngdev,你可以在任何文件中创建injector,但可能就在你需要它的地方