[英]Angular2 dependency injection, service not being injected during class inheritance
[英]Angular 2 dependency injection - A service is injected in some components but not in all
我正在開發一個Angular 2應用程序,該應用程序只有一個模塊,其中有幾個服務在bootstrap中注冊為提供者。 該應用程序還在同一模塊中使用這些服務的幾個組件。
所有組件都使用DI接收服務(服務在construtor中聲明為參數)。
我面臨的問題是:在某些組件中正確注入了相同的服務,但在其他組件中沒有。
我檢查了Injector對象中注入失敗的組件以及服務實例是否在Injector對象中。 失敗的是使用Injector.get()方法進行搜索。 作為參數提供的令牌與存儲在Injector字典中的令牌不同。 我無法找到原因,因為我使用的是服務的類名,而Javascript引擎會自動從此類名生成令牌。
我嘗試使用OpaqueTokens來控制注入,並且,即使我使用相同的不透明令牌,當調用Injector.get()方法時,參數提供的令牌被認為與注入器存儲的令牌不同。
代碼中的一個簡短片段看起來像
myservice.service.ts
import { OpaqueToken } from '@angular/core'
export const BACKEND = new OpaqueToken('backend');
app.module.ts
import { BACKEND } from 'myservice.service'
...
providers: [{ provide: BACKEND, useValue: "TestValue" }]
mycomponent.component.ts
import { Component, Inject } from '@angular/core'
import { BACKEND } from 'myservice.service'
@Component(
{
selector:'mycomponent'
templateUrl: ...
})
export class MyComponent
{
constructor(@Inject(BACKEND) config: string) {
console.info(JSON.stringify(config));
}
}
這種帶有BACKEND令牌的注入適用於某些組件,但對於其他組件則不適用(注入空{}對象)。 我試圖在瀏覽器中調試Javascript代碼,它看起來像是使用與字典中的令牌不同的令牌調用Injector(它們看起來相同,具有相同的名稱'后端'但仍然不同而且===返回false) 。
注意:我使用的是Angular 2.4.2,Typescript 2.1,帶有'commonjs'模塊和'node'模塊解析。 systemjs用作模塊加載器。
請你能提供一些關於如何解決這個問題的想法嗎?
謝謝,
您是否有來自不同模塊/組件的各種提供者聲明? 對於providers數組中的每個聲明,angular將創建這些服務的新實例。
你是否在@Injectable裝飾器中包含了括號? https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#injectable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.