关于sap:SAP-Spartacus-读取-Cart-的原理分析

3次阅读

共计 1577 个字符,预计需要花费 4 分钟才能阅读完成。

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 的原创文章,尽在:” 汪子熙 ”:

正文完
 0