PushTopicを登録
開発者コンソールの匿名Windowで実行
注意:Query中の項目に変更があった場合だけ、通知される。その他の項目を更新しても、通知されない。
PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'AccountUpdatePushTopic';
pushTopic.Query = 'SELECT Id, Name, Fax FROM Account';
pushTopic.ApiVersion = 57.0;
pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForOperationUpdate = true;
pushTopic.NotifyForOperationDelete = false;
pushTopic.NotifyForFields = 'Referenced';
insert pushTopic;
Aura componentを作成
cmp部分
※implements="flexipage:availableForAllPageTypes" 1つで良い
<aura:component implements="flexipage:availableForAllPageTypes" access="global">
<aura:attribute name="subscription" type="Object" />
<aura:attribute name="messages" type="List" default="[]" />
<lightning:empApi aura:id="empApi" />
<div class="slds-m-around_medium">
<lightning:button label="Subscribe PushTopic" onclick="{!c.handleSubscribe}" />
<lightning:button label="Unsubscribe PushTopic" onclick="{!c.handleUnsubscribe}" />
</div>
<div class="slds-m-around_medium">
<aura:iteration items="{!v.messages}" var="msg">
<p class="slds-box slds-box_xx-small slds-m-vertical_xx-small">
{!msg}
</p>
</aura:iteration>
</div>
</aura:component>
Controller js部分
({
handleSubscribe : function(component, event, helper) {
const empApi = component.find('empApi');
const channel = '/topic/AccountUpdatePushTopic'; // ★PushTopic API名に合わせる
const replayId = -1; // 最新から購読
const callback = function (message) {
console.log('Received PushTopic event:', JSON.stringify(message));
// 受信したイベントをmessagesリストに追加
let messages = component.get('v.messages') || [];
messages.unshift(JSON.stringify(message.data.sobject));
// ↑↑↑chatgptではmessage.payloadとなっているが、 ★★★★★message.data.sobjectが正しい
component.set('v.messages', messages);
};
empApi.subscribe(channel, replayId, callback).then(function (newSubscription) {
console.log('Subscribed to PushTopic channel:', channel);
component.set('v.subscription', newSubscription);
}).catch(function (error) {
console.error('Error subscribing to PushTopic:', error);
});
},
handleUnsubscribe : function(component, event, helper) {
const empApi = component.find('empApi');
const subscription = component.get('v.subscription');
empApi.unsubscribe(subscription, function (message) {
console.log('Unsubscribed from PushTopic channel');
});
}
})