从5分钟的快速启动开始,我一直在玩angular2 beta,遇到了一个让我难过的问题.
这是一个愚蠢的版本,显示我遇到的问题.首先,这是一个完美的hello world应用程序.
的package.json
{
"name": "...",
"version": "0.0.1",
"description": "...",
"author": {
"name": "...",
"email": "..."
},
"scripts": {
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
},
"license": "ISC",
"dependencies": {
"angular2": "2.0.0-beta.0",
"bootstrap": "^3.3.6",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "^0.1.2",
"rxjs": "5.0.0-beta.0",
"systemjs": "0.19.6",
"zone.js": "^0.5.10"
},
"devDependencies": {
"concurrently": "^1.0.0",
"lite-server": "^1.3.1",
"typescript": "^1.7.3"
}
}
Run Code Online (Sandbox Code Playgroud)
的index.html
<head>
<title>Title</title>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link href="styles.css" rel="stylesheet" …Run Code Online (Sandbox Code Playgroud) 在下面的类中,我想抽象出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 .