在下面的類中,我想抽象出http依賴性,以便Angular 2使用正常的依賴注入來注入http對象。Angular 2 - 在構造函數中使用其他參數混合依賴注入
import { Http } from '@angular/http';
class MyCollectionView<T> extends CollectionView {
constructor(private endpoint: string, private http: Http) {
}
// ... implemenation of class ...
}
我想使用類,如下所示:
class MyClass {
private collection: MyCollectionView<ITestRow>;
constructor() {
this.collection = new MyCollectionView<ITestRow>('/some/endpoint');
}
}
要在我目前的執行實例我必須寫
class MyClass {
private collection: MyCollectionView<ITestRow>;
constructor(private http: Http) {
this.collection = new MyCollectionView<ITestRow>('/some/endpoint', http);
}
}
據我知道這是不可能的在構造函數中結合ng2依賴注入和自定義參數。我想我需要某種工廠函數來照顧依賴注入部分,但到目前爲止我沒有運氣。特別是因爲課程也使用泛型。我可以在這裏遵循哪些最佳做法?
請注意,在單元測試中,應該仍然可以用MockBackend
代替DI。
我發現this question在stackoverflow,但其most upvoted answer不能用於恕我直言,因爲參數必須是動態的。
有道理,謝謝你的確認。由於這個類將始終是手動構建的,而不是通過依賴注入來構建,所以我將保持原樣。 :) – dotcs