2017-02-17 61 views
1

我在試圖瞭解@Host裝飾器如何工作與視圖組件解耦。所以,我創建了以下注入樹:@Host裝飾器如何在注入器樹中工作

class Dependency { 
} 

@Injectable() 
class NeedsDependency { 
    constructor(@Host() public dependency: Dependency) { 
    console.log(this.dependency); // outputs 'A', but I expected the error 
    } 
} 

const parent = ReflectiveInjector.resolveAndCreate([{provide: Dependency, useValue: 'A'}]); 
const child = parent.resolveAndCreateChild([]); 
const grandchild = child.resolveAndCreateChild([NeedsDependency]); 
grandchild.get(NeedsDependency); 

我希望得到一個錯誤,因爲我瞭解grandchild噴油器的主機child,並沒有在child噴油器提供Dependency。但是,當我運行此代碼時,我從根注入器中注入了'A'。爲什麼?

+0

提供了'NeedsDependency'('NgModel'或'Component')? –

+0

在這個例子中沒有角度框架,它是去耦的 –

+0

然後你不應該期望'@Host()'有任何效果。 –

回答

2

Host在普通噴油器上下文中沒有語義含義。

It is just ignored在編譯器外部使用時。

對於所期望的行爲,

我希望得到一個錯誤,因爲我瞭解孫子噴油器主機是孩子,並沒有在孩子噴油器提供的依賴。

改爲考慮使用Self

+0

得到它,謝謝,我想知道它是如何處理噴油器方面,然後在角度編譯器 –

+1

前段時間很好奇同樣的事情。具有指令/組件裝飾器的類獲得它們自己的注入器,並且構造器裝飾器[另外](https://github.com/angular/angular/blob/2.4.7/modules/%40angular/compiler/src/metadata_resolver.ts# L712-L727),包括編譯器相關的主機和屬性。 – estus

+0

太好了,謝謝你的鏈接,我會去探討。我希望有人會寫一本書來寫'angular'' angular1 –

0

指定噴射器應從任何噴油器檢索依賴性,直到到達當前組件的主機元素。

https://angular.io/docs/ts/latest/api/core/index/Host-decorator.html

聲音對我來說,它會尋找供應商望而止步它達到了元件的噴油器後。

+0

[看來這種行爲沒有發生到根。](https://stackoverflow.com/questions/47602697/angulars-host-decorator-not-reaching-the-top) –