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

Angular2: How to inject service that has no decorators to the app?

当尝试在 App 组件(我们正在 bootstrapping 的组件)中使用 Http 时,一切正常发现:

export default class AppComponent {

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

  getData() { 

  }
}

bootstrap(AppComponent, [HTTP_PROVIDERS]);

但是如果我用 CustomHttpService 包装 Http(并且当然将 CustomHttpService 添加到 bootstrap componenets 数组):

自定义-http-service.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

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

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

感谢 Eric Martinez 的评论和 this awesome explanation 我可以看到,当没有元数据附加到 class(带有装饰器)时,typescript 类型是不够的。

本文中提出的修复方法是将元数据添加到我们要注入的 class(在我的例子中是 CustomHttpService),这将变为:

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

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

  getData() { 

  }
}

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

bootstrap(AppComponent, [HTTP_PROVIDERS, CustomHttpService]);

现在可以了。