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

Shi*_*shi 2 angular

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

export default class AppComponent {

  constructor(public http: Http){
    console.log(this.http);
  }

  getData() { 

  }
}

bootstrap(AppComponent, [HTTP_PROVIDERS]);
Run Code Online (Sandbox Code Playgroud)

但是如果我用一个CustomHttpService(和ofcouse将CustomHttpService添加到bootstrap componentsnets数组)包装Http :

自定义HTTP-service.ts:

export default class CustomHttpService {

  constructor(public http: Http){
    console.log(this.http);
  }

  getData() { 

  }
}
Run Code Online (Sandbox Code Playgroud)

app.ts:

bootstrap(AppComponent, [CustomehttpService]);
Run Code Online (Sandbox Code Playgroud)

我越来越:

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
Run Code Online (Sandbox Code Playgroud)

我错过了什么?是不是足以导入模块并在引导功能中注册自定义服务?

这个问题与我们想要注入我们的应用程序的没有元数据(组件,视图等)的每个类相关.

Shi*_*shi 5

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

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

@Injectable() // from angluar2/core
export default class CustomHttpService {

  constructor(public http: Http){
    console.log(this.http);
  }

  getData() { 

  }
}
Run Code Online (Sandbox Code Playgroud)

当然要在bootstrap函数中将服务添加到injectables数组:

bootstrap(AppComponent, [HTTP_PROVIDERS, CustomHttpService]);
Run Code Online (Sandbox Code Playgroud)

现在它的工作原理.