[英]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.