天天看點

SAP Spartacus 事件服務 Event Service 使用介紹

官方連結: https://sap.github.io/spartacus-docs/event-service/#page-title

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 購物車),然後将所有購物車資料附加到事件資料:

c

繼續閱讀