[英]Why does HTTP service require @Injectable decorator and a custom service does not in Angular2
为什么在使用http
进行 DI 时需要包含@Injectable
,而在使用我创建的自定义服务进行 DI 时不需要它?
例如:
//no @Injectable() here
export class Test {
constructor(private customService: CustomService){}
}
/*-------------*/
@Injectable() // <== required here
export class HttpTest {
constructor(private http: Http){}
}
如果构造函数中有需要注入的参数,则需要@Injectable()
。 看看为什么@Injectable()
@Injectable()
将类标记为可用于注入器以进行实例化。 一般而言,注入器在尝试实例化未标记为@Injectable()
的类时会报告错误。碰巧,你可以省略
@Injectable()
从第一个版本HeroService
因为它没有注入参数。 但是您现在必须拥有它,因为该服务具有注入的依赖项。 您需要它,因为 Angular 需要构造函数参数元数据才能注入Logger
。
您的示例不起作用,因为它需要在Test
类上使用@Injectable()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.