为什么Http服务需要@Injectable装饰器而自定义服务不在Angular2中

时间:2017-05-28 19:42:04

标签: angular typescript dependency-injection

为什么在使用@Injectable进行DI时我需要包含Http,但在使用我创建的自定义服务进行DI时我不需要它?

例如

//no @Injectable() here
export class Test {
 constructor(private customService: CustomService){}
}

/*-------------*/

@Injectable() // <== required here
export class HttpTest {
 constructor(private http: Http){}
}

1 个答案:

答案 0 :(得分:1)

如果在构造函数中有一个需要注入的参数,则需要

@Injectable()。见Why @Injectable()

  

@Injectable()标记一个类可用于注入器   实例。一般来说,注射器在何时报告错误   尝试实例化未标记为@Injectable()的类。

     

碰巧,你可以从第一个中省略@Injectable()   HeroService的版本,因为它没有注入参数。但是你   现在必须拥有该服务具有注入依赖项。你需要   因为Angular需要构造函数参数元数据   注入Logger

您的示例无效,因为它需要@Injectable()

上的Test
相关问题