Angular2:如何向应用程序注入没有装饰器的服务



当尝试在应用程序组件(我们正在引导的组件)中使用Http时,一切都可以找到:

export default class AppComponent {
  constructor(public http: Http){
    console.log(this.http);
  }
  getData() { 
  }
}
bootstrap(AppComponent, [HTTP_PROVIDERS]);

但是,如果我用CustomHttpService包装Http(并且理所当然地将CustomHttpService添加到引导组件数组中):

自定义http服务.ts:

export default class CustomHttpService {
  constructor(public http: Http){
    console.log(this.http);
  }
  getData() { 
  }
}

app.ts

bootstrap(AppComponent, [CustomehttpService]);

我得到:

NoAnnotationError {message: "Cannot resolve all parameters for CustomHttpServic…ake sure they all have valid type or annotations.", stack: $
## _onError ##
TypeError: Cannot read property 'get' of undefined
    at angular2.dev.js:19620
    at Zone.run (angular2.dev.js:138)
    at Zone.run (angular2.dev.js:10644)
    at NgZone.run (angular2.dev.js:10607)
    at ApplicationRef_.bootstrap (angular2.dev.js:19615)
    at Object.commonBootstrap (angular2.dev.js:26650)
    at Object.bootstrap (angular2.dev.js:27475)
    at Object.<anonymous> (app.ts:23)
    at app.ts:23
    at SystemJSLoader.__exec (system.src.js:1384)
Uncaught TypeError: Cannot read property 'get' of undefined

我错过了什么?这还不足以导入模块并在引导函数中注册自定义服务吗?

这个问题与我们要注入到应用程序中的每个没有元数据的类(组件、视图等)有关。

感谢Eric Martinez的评论和这一令人敬畏的解释,我可以看到,当没有元数据附加到类(使用装饰器)时,typescript类型是不够的。

本文中提出的修复方法是将元数据添加到我们想要注入的类中(在我的情况下,这是CustomHttpService),这将变成:

@Injectable() // from angluar2/core
export default class CustomHttpService {
  constructor(public http: Http){
    console.log(this.http);
  }
  getData() { 
  }
}

当然,在引导功能中将服务添加到可注射阵列:

bootstrap(AppComponent, [HTTP_PROVIDERS, CustomHttpService]);

现在它起作用了。

最新更新