如何获取 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(