本文介绍了Angular2:如何注入一个没有装饰的应用服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图在App组件(组件,我们自举)一切正常发现使用 HTTP

When trying to use Http in the App component (the component we are bootstrapping) everything works find:

export default class AppComponent {

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

  getData() { 

  }
}

bootstrap(AppComponent, [HTTP_PROVIDERS]);

但是,如果我换的Http以 CustomHttpService (和ofcouse添加到CustomHttpService引导其它的组件阵列):

But if I wrap Http with a CustomHttpService (and ofcouse add CustomHttpService to the bootstrap componenets array):

自定义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

我在想什么?难道这还不够导入模块和注册自定义服务的引导作用?

What am I missing? Isn't that enough to import modules and register the custom service in the bootstrap function?

此问题是适用于每一个有没有元数据类(组件,浏览等),我们要注入到我们的应用程序。

This question is relevant to every class that has no metadata (Component, View etc.. ) we want to inject to our application.

推荐答案

感谢埃里克·马丁内斯评论和this真棒解释我看得出来,在没有元数据附加到类(装饰)的打字稿类型是不够的。

Thanks to Eric Martinez comment and this awesome explanation I could see that the typescript types are not enough when no meta-data is attached to the class (with decorators).

在这篇文章中提出的解决方法是元数据添加到我们要注入的类(在此我的情况是 CustomHttpService ),这将成为:

The fix proposed in this article is to add metadata to the class we want to inject (in my case this is the CustomHttpService) and this will become:

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

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

  getData() { 

  }
}

和当然的服务添加到自举功能的注射数组:

and of course to add the service to the injectables array in the bootstrap function:

bootstrap(AppComponent, [HTTP_PROVIDERS, CustomHttpService]);

和现在的作品。

这篇关于Angular2:如何注入一个没有装饰的应用服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:14