SAP Spartacus 里的 cxOutletRef 指令执行过程分析
先看 cxOutletRef 指令的效果:ng-template 里定義了如下圖標 1 區域所示的自定義 UI,通過 cxOutletRef, 將其插入到圖標 2 所示的 ProductDetailsPageTemplate里:
源代碼:
<ng-template cxOutletRef="ProductDetailsPageTemplate" cxOutletPos="before" let-model><div class="before-pdp">Campaign UI for Canon</div><div class="after-pdp">{{ model.component | async | json }}</div></ng-template>運行時的效果:
查看源代碼,發現該指令的有效實現不多,僅僅調用 OutletService.add 方法:
仔細閱讀 add 方法的三個參數:
outlet:代表自定義 UI 插入的 UI 位置,通過字符串代表。可以將 template 或者 ComponentFactory 插入該字符串代表的 UI 位置。
tpl: 待插入的自定義 UI 所在的頁面模板實例。
index.html 頁面里只有一個 cx-storefront selector, 對應 StorefrontComponent:
Outlet.service.ts 里維護了一個字典結構,key 為 outlet 名稱,值為 cxOutletRef 指令所在的 ng-template 實例。
Storefront Component refresh 時,會調用 hook,包含施加在其上的 Directive:
通過 Angular 標準的 ngOnChanges lifecycle hook,觸發該 cxOutlet Directive 的 render 方法:
在渲染 embedded view 時,如果遇到該視圖包含了 cxOutlefRef 指令,就觸發依賴注入機制,生成該指令的實例。
從 Angular 內部變量 _lView 里,我們可以輕易辨別出當前 ng_template 實例代表的頁面:
比如這個高亮的結構:
對應了 HTML 里這段 ng-template 聲明:
而 div.after-pdp 及 text, JsonPipe 和 AsyncPipe:
對應 template 里這段代碼:
直接在 .html 文件里設置斷點:
在最新版本的 Chrome 里,這些斷點可以直接觸發了:
在渲染 cxOutletRef 指向的 ProductDetailsPageTemplate 時,會觸發 outlet Directive 的 ngOnChanges 方法:
這一切,都歸功于 SAP Spartacus 獨特的設計,即所有 Angular Component,都通過 PageLayoutComponent 進行渲染:
而 PageLayoutComponent 實現里,包含了 cxOutlet 的消費:
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的SAP Spartacus 里的 cxOutletRef 指令执行过程分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是激光技术
- 下一篇: 高速上违规使用理想“自动驾驶”致撞车!车