dot*_*tcs 17 dependency-injection typescript angular
在下面的类中,我想抽象出http依赖关系,这样Angular 2就会使用普通的依赖注入来注入http对象.
import { Http } from '@angular/http';
class MyCollectionView<T> extends CollectionView {
constructor(private endpoint: string, private http: Http) {
}
// ... implemenation of class ...
}
Run Code Online (Sandbox Code Playgroud)
我想用这个课程如下:
class MyClass {
private collection: MyCollectionView<ITestRow>;
constructor() {
this.collection = new MyCollectionView<ITestRow>('/some/endpoint');
}
}
Run Code Online (Sandbox Code Playgroud)
要在我当前的实现中实例化,我必须写
class MyClass {
private collection: MyCollectionView<ITestRow>;
constructor(private http: Http) {
this.collection = new MyCollectionView<ITestRow>('/some/endpoint', http);
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,不可能在构造函数中组合ng2依赖注入和自定义参数.我想我需要某种工厂功能来处理依赖注入部分,但到目前为止我没有运气.特别是因为该课程也使用了泛型.我可以遵循哪些最佳做法?
请注意,在单元测试中,仍然可以用MockBackend相反的方法来解析DI .
Gün*_*uer 14
依赖注入(DI)仅适用于DI创建的类.如果您创建类new Xxx(),则不会发生DI.
如果实例是由DI创建的,那么您无法传递自己的参数.
您需要为DI创建这些参数的提供程序才能注入它们.
你正在做的是正确的方法.
| 归档时间: |
|
| 查看次数: |
3507 次 |
| 最近记录: |