在 Storefront AppModule 构造函数里注入 ActiveCartService:

private cartService: ActiveCartService,


调用其 API:

const loading$ = this.cartService.getLoading();        loading$.subscribe((data) => console.log('Jerry cart loading? ', data));

打印出的日志:

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 entity  protected 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 === null    filter((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的原创文章,尽在:"汪子熙":