本文作為學習的感悟記錄,閱讀本文之前需要熟讀相關的官方文檔。
- declearable(components, directives, pipes)的作用域由NgModule來控制,而service的作用域由分層依賴注入機制來控制。
- 每一個component實例都有一個注入器,因此一個component tree對應了一個與之平行的injector tree。相關文檔
組件的注入器可能是一個injector tree中更高級的祖先注入器的代理(如果某個component本身沒有
providers
),但這只是提升效率的實現細節,我們不用在乎這點差異,在你的腦海里只要想象成每個組件都有自己的注入器就可以了。
- root module和其他eagerly loaded module的providers都注冊在application root injector,因此在其中一個NgModule中注冊的service是全局共享的(相關文檔)。(而在lazy loaded module中注冊的service則僅僅局限于這個模塊,后面會談到)
注入器樹
可以大致理解為最頂層是platform的注入器,然后下一層是application root injector,然后下面才是組件注入器樹。(在Platform Injector中注冊的是Angular內部使用的一些服務,開發者一般不需要與它打交道)(一個頁面最多有1個Platform,一個Platform中可以有多個Application,但是絕大多數時候我們只需要創建一個Application)
包含lazy loaded module的注入器樹
每一個lazy loaded module有一個自己的注入器,這個注入器繼承上一個level的module注入器。最高level是eagerly loaded module,下一level是在eagerly loaded modules的路由定義中loadChildren指定的那些lazy modules,再下一level就是上一層lazy modules的路由定義中loadChildren指定的那些lazy modules,依此類推。
每一層的module injector下面就是一顆(與component tree相同結構、一一對應的)injector tree。
我們可以將provider注冊在module injector中,也可以注冊在injector tree的某一個節點上。 相關文檔
- NgModule的providers注冊的順序:先注冊imported modules中的providers(按照imports數組中的順序),再注冊NgModule.providers數組中的provider,如果注冊了重復的provider token,后注冊的覆蓋先注冊的。相關文檔
- @Injectable的作用是在編譯時讓TypeScript編譯器將constructor中的依賴信息保存在class metadata中,運行時注入器通過metadata中的信息來決定注入什么。如果service1需要在constructor中注入service2但service1卻沒有任何裝飾器,那么TypeScript編譯器就不會保存service1的依賴信息,那么在運行時創建service1的時候就會報錯(注入器不知道要注入什么)。相關文檔
- 除了可以用
被注入的class本身
或InjectionToken作為Provider token以外,使用class-interface也能獲得諸多好處(為編輯器提供editor tooling,narrowing interface有助于解耦,占用資源少,可以用來注入父組件)。 - 如果attribute directive被應用在component element上時(
<my-component my-directive1 my-directive2></my-component>
)這些指令與組件共用同一個注入器。因此我們可以用attribute directive的providers array
來"擴展"compoent的providers array
。這篇文章將attribute directive與component之間的協作寫得很清楚了。
還有很多細節沒有搞清楚,比如:
- @Host究竟能查找到哪一個注入器(其表現與官方文檔說明的不太一樣,經過實驗發現它能找到parent element上注冊的providers、parent component上的viewProviders,卻找不到parent component上的providers,存在transclusion的時候又復雜一些)
- 為什么在同一個element上的component、directive能共用同一個注入器
- 注入PlatformRef,ApplicationRef,NgModuleRef,Injector得到的對象中都有與injector相關的屬性,這些injector有什么聯系。
- 如果有一個directive掛載在一個普通element上,并且這個directive有providers數組,那么是否會在這個element上創建一個新的injector。
- 對于一個component來說,它的host element和host component分別是什么。
這些問題目前還沒有在網上找到答案,可能需要研究源碼才能解答了。
參考資料
https://stackoverflow.com/questions/36455305/accessing-root-angular-2-injector-instance-globally
https://blog.thoughtram.io/angular/2015/08/20/host-and-visibility-in-angular-2-dependency-injection.html
https://angular-2-training-book.rangle.io/handout/di/angular2/the_injector_tree.html (此頁面尾部有一個很好用的在線例子)
https://medium.com/@ttemplier/component-composition-in-angular2-part-1-33f50f402906
https://stackoverflow.com/questions/44530654/angular-service-injecting-dynamic-component
https://stackoverflow.com/questions/45345163/angular-compiler-options