SAP Spartacus 读取 Cart 的原理分析
App.module.ts 的源代碼:
export class AppModule { constructor(private config: DebugConfig,private actions$: Actions,private cartService: ActiveCartService){// console.log('Jerry config: ', this.config);this.actions$.pipe(ofType(CartActions.LOAD_CART),map((action: CartActions.LoadCart) => action.payload),tap((data) => console.log('Jerry cart: ' , data))).subscribe();this.cartService.getLoading().subscribe((data) => console.log('Jerry cart loading? ', data));}}首先執行 ofType,這本質是一個 filter 操作:
數組的 some 方法:檢查數組元素是否滿足 predicate 函數指定的條件
然后執行 map 操作,返回一個 OperatorFunction,作為 pipe 的輸入條件之一:
觸發點:
quantity 的值來自 activeCartService 維護的 active cart 的 deliveryItemsQuantity 字段。
執行 Async pipe:
async pipe 的 transform 方法會調用 subscribe 方法:
createSubscription 最終會調用:
getActive 返回:
activeCart$ 的值來自 activeCartLoading$ 和 activeCartValue$ 兩部分。
activeCartLoading$ 負責加載 cart,見代碼第 139 行。
調用的是 ActiveCartService 的 loadCart 方法:
給 store 發送一個 action。
LoadCart 擴展自 EntityLoadAction,除了 payload 之外,定義了額外的字段:
比如 meta:
如果想打印出加載成功的購物車信息:
const action2 = this.actions$.pipe(ofType(CartActions.LOAD_CART_SUCCESS),map((action: CartActions.LoadCartSuccess) => action.payload),tap((data) => console.log('Jerry cart SUCCESS: ' , data)));action2.subscribe();const action3 = this.actions$.pipe(ofType(CartActions.LOAD_CARTS_SUCCESS),map((action: CartActions.LoadCartsSuccess) => action.payload),tap((data) => console.log('Jerry carts SUCCESS: ' , data)));action3.subscribe();結果:
那么,這個加載成功的 Cart 數據,是如何通過 action 實例 subscribe 之后被讀取出來的呢?
顯然,單步調試第73行代碼,并不會看到我們想了解的明細。因為 subscribe 只是觸發 cart 的加載,而后者是一個異步過程。
F8之后斷點再次觸發時,cart 數據已經出現在 payload 里了。但是我們不知道是誰從哪里通過什么樣的方式進行的回調。
在 subscriber 的實現里,能看到當前已經 ready 的 state 值:
ngrx-store.js 在這里將 state 片段的 carts 傳入 map 回調函數里:
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的SAP Spartacus 读取 Cart 的原理分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL查询左连接、右连接、内连接[通俗易
- 下一篇: SAP Spartacus 成功读取 C