Angular 在另一个服务中注入服务
我尝试使用angular 2的DI将一个服务注入另一个服务Angular 在另一个服务中注入服务,angular,typescript,Angular,Typescript,我尝试使用angular 2的DI将一个服务注入另一个服务 import {HttpService} from 'scripts/httpService'; export class CurrentBlog{ constructor(public httpService:HttpService){} } 当我执行此操作时,会出现以下错误: 无法解析CurrentBlog(?)的所有参数。确保它们都具有有效的类型或批注 我已经用普通组件测试了DI,它工作得很好。 但当我把它注入服务时。它
import {HttpService} from 'scripts/httpService';
export class CurrentBlog{
constructor(public httpService:HttpService){}
}
当我执行此操作时,会出现以下错误:
无法解析CurrentBlog(?)的所有参数。确保它们都具有有效的类型或批注
我已经用普通组件测试了DI,它工作得很好。
但当我把它注入服务时。它根本不起作用。在这种情况下,仅使用DI是不够的。下面的链接解决了相同的问题: 所以它说: TypeScript在设置emitDecoratorMetadata选项时生成元数据。然而,这并不意味着它会盲目地为代码中的每个类或方法生成元数据。当装饰程序实际附加到特定代码时,TypeScript仅为类、方法、属性或方法/构造函数参数生成元数据。否则,将生成大量未使用的元数据代码,这不仅会影响文件大小,还会影响应用程序运行时 因此,为了强制生成Metadta,我们可以尝试放置以下两种注释之一:
import {HttpService} from 'scripts/httpService';
import {Inject} from 'angular2/core';
export class CurrentBlog{
constructor(@Inject(HttpService) public httpService:HttpService){}
}
或者
在angular 2中,您需要让angular喷油器了解您的服务。为此,您需要将服务标记为可注入的 HttpService
import {Injectable} from 'angular2/angular2';
@Injectable()
export class HttpService{
...
}
当前博客
import {HttpService} from 'scripts/httpService';
import {Inject} from 'angular2/core';
export class CurrentBlog{
constructor(public httpService:HttpService){}
}
这不起作用,因为Angular2会抱怨HttpService没有提供程序代码>。
import {HttpService} from 'scripts/httpService';
import {Inject} from 'angular2/core';
export class CurrentBlog{
constructor(public httpService:HttpService){}
}