头图

Inject ActiveCartService in the Storefront AppModule constructor:

private cartService: ActiveCartService,


Call its API:

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

Printed log:

Active-cart.service.d.ts contains only the parameter definition of the method:

If you want to view its implementation code, you still have to go to the Spartacus-core.js file of fesm2015 to view:

getLoading(): Observable<boolean> {
    return this.cartSelector$.pipe(
      map((cartEntity) => cartEntity.loading),
      distinctUntilChanged()
    );
  }

View the implementation of this.cartSelector$:

// Stream with active cart entity
  protected cartSelector$ = this.activeCartId$.pipe(
    switchMap((cartId) => this.multiCartService.getCartEntity(cartId))
  );

The assignment logic of cartSelector$: Take out cartId from activeCartId$ and call multiCartService to read it.

MultiCartService is only read from the store through the selector.

Assignment logic of 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;
    })
  );

Add a line of print statement to this file:

Sure enough, I saw this sentence:

Why the initial loading flag is true?

Knowing through debugging code:

This LoadCart inherits EntityLoadAction, so it also inherits the default load: true flag.

So when does it become false again?

After reading the call stack, I didn't see any Spartacus related code:

Only know that it must happen after Load Cart Success.

I saw a clue from map.js: this value contains the business data of the shopping cart:

And loading: false

This is our application code:

Take out the CartEntity from the Cart selector, call map, and map the loading field:

Cart data structure:

It can also be explained from this that it must be the second loading print triggered by Load Cart Success:

At this point, the cart data has returned, and loading is false:

More original articles by Jerry, all in: "Wang Zixi":


注销
1k 声望1.6k 粉丝

invalid