Mar*_*yer 12 javascript dependency-injection angular
我有一个表示模型的typescript类,我希望实例通过angular的Http服务与API通信.
但是模型的构造函数在创建实例时需要参数.例如一些超级简单:
class SomeModel{
constructor(public id:number, public name:string, ){
}
Run Code Online (Sandbox Code Playgroud)
我想注入Http服务,以便它可用于我的实例,但似乎这样做的规范方法是使用以下命令构造器:
constructor(http:Http)
Run Code Online (Sandbox Code Playgroud)
我一直在挖掘Injector文档,但它有点稀疏,我没有发现任何有用的东西.有没有办法在Http不使用构造函数模式的情况下从DI系统获取对服务的引用?
更新
HTTP_PROVIDERS早已不复存在。
HttpClientModule是当前的替代品。
原来的
如果您注入具有构造函数参数的类,则@Injectable需要添加注释。
@Injectable()
class SomeModel{
// constructor(public id:number, public name:string, ){
// }
constructor(http:Http) {}
}
Run Code Online (Sandbox Code Playgroud)
为此,HTTP_PROVIDERS需要添加到bootstrap(AppComponent, [HTTP_PROVIDERS]);
另请参阅Angular2 beta - 引导 HTTP_PROVIDERS - “意外令牌 <”
如果您需要从组件传递其他参数,则可以使用函数传递它们。
另一种方法是手动创建实例并向Http注入器请求。
export class MyComponent {
constructor(injector: Injector) {
this.someModel = new SomeModel(Injector.resolveAndCreate(Http), 1, 2);
}
}
Run Code Online (Sandbox Code Playgroud)