【问题标题】:Angular2: How to inject service that has no decorators to the app?Angular2:如何向应用程序注入没有装饰器的服务?
【发布时间】:2016-02-02 20:30:07
【问题描述】:

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

export default class AppComponent {

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

  getData() { 

  }
}

bootstrap(AppComponent, [HTTP_PROVIDERS]);

但如果我用 CustomHttpService 包装 Http(并且经常将 CustomHttpService 添加到引导组件数组):

custom-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 函数中导入模块和注册自定义服务还不够吗?

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

【问题讨论】:

  • 你应该阅读这个article,准确解释你所看到的。
  • @EricMartinez。这是完美的!

标签: angular


【解决方案1】:

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

本文提出的解决方法是将元数据添加到我们要注入的类(在我的例子中是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]);

现在它可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 2020-01-18
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2019-05-06
    • 2018-07-30
    • 2018-01-07
    相关资源
    最近更新 更多