关于sap:SAP-Spartacus-事件服务-Event-Service-使用介绍

2次阅读

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

官网链接:https://sap.github.io/spartac…

The Spartacus event service provides a stream of events that you can consume without a tight integration to specific components or modules. The event system is used in Spartacus to build integrations to third party systems, such as tag managers and web trackers.

Spartacus 事件服务提供了一个事件流,您能够应用这些事件流,而无需与特定组件或模块严密集成。Spartacus 中应用事件零碎来构建与第三方零碎的集成,例如标签管理器和网络跟踪器。

The event service also allows you to decouple certain components. For example, you might have a component that dispatches an event, and another component that reacts to this event, without requiring any hard dependency between the components.

事件服务还容许您解耦某些组件。例如,您可能有一个分派事件的组件和另一个对该事件做出反馈的组件,而无需组件之间的任何硬依赖。

一个例子:

import {CxEvent} from "@spartacus/core";
export class CartAddEntryEvent extends CxEvent {
  cartId: string;
  userId: string;
  productCode: string;
  quantity: number;
}

在 app module 里监听这个事件的代码:

export class AppModule {constructor(events: EventService, myAdapter: OccCartAdapter) {const result$ = events.get(CartAddEntrySuccessEvent);
    result$.subscribe((event) => console.log(event));
  }
}

运行时,我一旦将某个产品加到购物车里,就会触发下面 app module 里注册的匿名函数的 console.log, 打印出 CartAddEntrySuccessEvent 实例的值。

Pulling Additional Data From Facades – 从 Facade 中提取额定数据

如果您须要比特定事件中蕴含的数据更多的数据,您能够将此数据与其余流组合。例如,您能够从 facade 收集额定的数据。

以下是对“增加到购物车事件”做出反馈的示例,而后期待购物车 stable(因为须要从后端从新加载 OCC 购物车),而后将所有购物车数据附加到事件数据:

constructor(
    events: EventService,
    cartService: ActiveCartService
    ){}
/* ... */

const result$ = this.events.get(CartAddEntrySuccessEvent).pipe(
    // When the above event is captured, wait for the cart to be stable
    // (because OCC reloads the cart after any cart operation)...
    switchMap((event) =>
        this.cartService.isStable().pipe(filter(Boolean), mapTo(event))
    ),
    // Merge the state snapshot of the cart with the data from the event:
    withLatestFrom(this.cartService.getActive()),
    map(([event, cart]) => ({...event, cart}))
);

运行时成果:

更多 Jerry 的原创文章,尽在:” 汪子熙 ”:

正文完
 0