SAP Spartacus 事件服务 Event Service 使用介绍

官方链接: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的原创文章,尽在:"汪子熙":

你可能感兴趣的:(SAP Spartacus 事件服务 Event Service 使用介绍)