topicの登録は empApi PushTopic を参考
LWCを作成
<template>
<lightning-button label="Subscribe PushTopic" onclick={handleSubscribe}></lightning-button>
<lightning-button label="Unsubscribe PushTopic" onclick={handleUnsubscribe}></lightning-button>
<template for:each={messages} for:item="msg">
<p key={msg} class="slds-box slds-box_xx-small slds-m-vertical_xx-small">
{msg}
</p>
</template>
</template>
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class MyPushTopicListener extends LightningElement {
subscription = null;
messages = [];
// 初期化(LWCにおけるcomponentDidMountのような役割)
connectedCallback() {
// イベントエラー時の処理
onError((error) => {
console.error("Error in EmpApi: ", error);
});
}
// PushTopicの購読
handleSubscribe() {
const channel = '/topic/AccountUpdatePushTopic'; // 使用するPushTopic名を指定
const replayId = -1; // 最新のメッセージから購読
// 購読して、メッセージを受け取る
subscribe(channel, replayId, (message) => {
console.log('Received message: ', JSON.stringify(message));
// 受信したメッセージをmessagesリストに追加
this.messages = [JSON.stringify(message.data.sobject), ...this.messages];
}).then((response) => {
console.log('Successfully subscribed to channel: ', channel);
this.subscription = response;
});
}
// PushTopicの購読解除
handleUnsubscribe() {
if (this.subscription) {
unsubscribe(this.subscription, (response) => {
console.log('Unsubscribed from channel: ', response);
});
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>63.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__RecordAction</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>