如何获取 SAP Commerce Cloud Spartacus UI 购物车 Cart 的加载状态
在 Storefront AppModule 構造函數里注入 ActiveCartService:
private cartService: ActiveCartService,
調用其 API:
打印出的日志:
active-cart.service.d.ts 里,僅僅包含方法的參數定義:
如果要查看其實現代碼,還是得去 fesm2015 的 Spartacus-core.js 文件里查看:
getLoading(): Observable<boolean> {return this.cartSelector$.pipe(map((cartEntity) => cartEntity.loading),distinctUntilChanged());}查看 this.cartSelector$ 的實現:
// Stream with active cart entityprotected cartSelector$ = this.activeCartId$.pipe(switchMap((cartId) => this.multiCartService.getCartEntity(cartId)));cartSelector$ 的賦值邏輯:從 activeCartId$ 里取出 cartId,調用 multiCartService 讀取。
MultiCartService 也只是從 store 里通過selector 去讀取。
ActiveCartId$ 的賦值邏輯:
// This stream is used for referencing carts in API calls.protected activeCartId$ = this.userIdService.getUserId().pipe(// We want to wait with initialization of cartId until we have userId initialized// We have take(1) to not trigger this stream, when userId changes.take(1),switchMapTo(this.store),select(MultiCartSelectors.getActiveCartId),// We also wait until we initialize cart from localStorage. Before that happens cartId in store === nullfilter((cartId) => cartId !== activeCartInitialState),map((cartId) => {if (cartId === '') {// We fallback to current when we don't have particular cart id -> cartId === '', because that's how you reference latest user cart.return OCC_CART_ID_CURRENT;}return cartId;}));在這個文件處加上一行打印語句:
果然看到這條語句了:
為什么初始的 loading 標志位為 true?
通過調試代碼得知:
這個 LoadCart 繼承了 EntityLoadAction,所以也繼承了默認的 load:true 標志位。
那么什么時候又變成 false 呢?
調用棧看完了都沒看到有 Spartacus 相關的代碼:
只知道肯定發生在 Load Cart Success 之后。
從 map.js 里看到了線索:這個 value 里包含了購物車 cart 的業務數據:
以及 loading:false
這是我們的應用代碼:
從 Cart selector 里取出 CartEntity,調用 map,將 loading 字段映射出來:
Cart 數據結構:
從這里也能說明,一定是 Load Cart Success 觸發的第二次 loading 打印:
此時 cart 數據已經回來了,loading 為 false:
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的如何获取 SAP Commerce Cloud Spartacus UI 购物车 Cart 的加载状态的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 活下去新手攻略 前期干什么
- 下一篇: NgRx 里 first 和 take(