0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

empApi PushTopic LWC

Posted at

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>

LWCコンポーネントを画面に追加、今回はホーム画面に追加

image.png

新規でAccountを追加、または、Faxを変更するとMsgが↑↑↑ように表示される

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?