[英]Inject services in another service angular 2
I tried injecting one service in another using DI of angular 2 我尝试使用角度为2的DI在另一个服务中注入一个服务
import {HttpService} from 'scripts/httpService';
export class CurrentBlog{
constructor(public httpService:HttpService){}
}
When I do this, I get this error : 当我这样做时,我收到此错误:
Cannot resolve all parameters for CurrentBlog(?).
无法解析CurrentBlog(?)的所有参数。 Make sure they all have valid type or annotations.
确保它们都具有有效的类型或注释。
I have tested DI with normal components and it works fine. 我用正常的组件测试了DI,它工作正常。 But when I inject it in service.
但是当我注入服务时。 It simply doesn't work.
它根本不起作用。
In angular 2 you need to make the angular injector aware of your service. 在角度2中,您需要使角度注射器了解您的服务。 To do this you need to mark the service as Injectable.
为此,您需要将服务标记为“可注入”。
HttpService HttpService的
import {Injectable} from 'angular2/angular2';
@Injectable()
export class HttpService{
...
}
CurrentBlog CurrentBlog
import {HttpService} from 'scripts/httpService';
import {Inject} from 'angular2/core';
export class CurrentBlog{
constructor(public httpService:HttpService){}
}
In this case just DI won't be enough. 在这种情况下,只有DI是不够的。 This link below addresses the same problem :
以下链接解决了同样的问题:
http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html
So it says : 所以它说:
TypeScript generates metadata when the emitDecoratorMetadata option is set. 设置emitDecoratorMetadata选项时,TypeScript会生成元数据。 However, that doesn't mean that it generates metadata blindly for each and every class or method of our code.
但是,这并不意味着它会盲目地为我们代码的每个类或方法生成元数据。 TypeScript only generates metadata for a class, method, property or method/constructor parameter when a decorator is actually attached to that particular code.
当装饰器实际附加到该特定代码时,TypeScript仅为类,方法,属性或方法/构造函数参数生成元数据。 Otherwise, a huge amount of unused metadata code would be generated, which not only affects file size, but it'd also have an impact on our application runtime.
否则,将生成大量未使用的元数据代码,这不仅会影响文件大小,而且还会对我们的应用程序运行时产生影响。
So to enforce Metadta Generations we can try putting either of the following two annotations : 因此,为了强制执行Metadta Generations,我们可以尝试使用以下两个注释中的任何一个:
import {HttpService} from 'scripts/httpService';
import {Inject} from 'angular2/core';
export class CurrentBlog{
constructor(@Inject(HttpService) public httpService:HttpService){}
}
Or, 要么,
import {Injectable} from 'angular2/core';
import {HttpService} from 'scripts/httpService';
@Injectable()
export class CurrentBlog{
constructor(public httpService:HttpService){}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.