Monday, 21 June 2021

How to Subscribe to a Platform Event from LWC

 Hi ,

Here we are going to learn how to subscribe to a Platform Event from LWC.


To subscribe for a Platform Event we have to import following methods from "lightning/empApi" module


  • subscribe
  • unsubscribe
  • onError
  • setDebugFlag
  • isEmpEnabled


Source Code:

HTML file:

<template> 

    <lightning-card title="EmpApi Example" icon-name="custom:custom14">
      
        <div class="slds-m-around_medium">
           
            <div class="slds-p-around_medium lgc-bg">
                <lightning-tile label="Account" href="/path/to/somewhere">
                <p class="slds-truncate" title="7 Members"> {accountName}</p>
                </lightning-tile>
            </div>
            <lightning-button variant="destructive" label="Unsubscribe" title="Unsubscribe"
                onclick={handleUnsubscribe} disabled={isUnsubscribeDisabled}
                class="slds-m-left_x-small"></lightning-button>
        </div>
    </lightning-card>
</template>



Javscript File:

import { LightningElement,track,api } from 'lwc';
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from 'lightning/empApi';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class PlatformEventExample extends LightningElement {
    channelName = '/event/TestEvent__e';
    isSubscribeDisabled = false;
    isUnsubscribeDisabled = !this.isSubscribeDisabled;
    subscription = {};
    @api accountName;
    // Tracks changes to channelName text field
    handleChannelName(event) {
        this.channelName = event.target.value;
    }
     // Initializes the component
     connectedCallback() {       
        // Register error listener       
        this.registerErrorListener();     
        this.handleSubscribe(); 
    }
// Handles subscribe button click
     handleSubscribe() {
                 // Callback invoked whenever a new event message is received
        

        // Invoke subscribe method of empApi. Pass reference to messageCallback
        subscribe(this.channelName, -1, this.messageCallback).then(response => {
            // Response contains the subscription information on subscribe call
            console.log('Subscription request sent to: ', JSON.stringify(response.channel));
            this.subscription = response;
            this.toggleSubscribeButton(true);
        });
    }
     // Handles unsubscribe button click
     handleUnsubscribe() {
        this.toggleSubscribeButton(false);

        // Invoke unsubscribe method of empApi
        unsubscribe(this.subscription, response => {
            console.log('unsubscribe() response: ', JSON.stringify(response));
            // Response is true for successful unsubscribe
        });
    }
    registerErrorListener() {
        // Invoke onError empApi method
        onError(error => {
            console.log('Received error from server: ', JSON.stringify(error));
            // Error contains the server-side error
        });
    }
    toggleSubscribeButton(enableSubscribe) {
        this.isSubscribeDisabled = enableSubscribe;
        this.isUnsubscribeDisabled = !enableSubscribe;
    }

    messageCallback  = (response) => {
        console.log('New message received : ', JSON.stringify(response));       
        this.accountName = response.data.payload.RecordChange__c;
        const toastEvent = new ShowToastEvent({
            title: 'Success!',
            message: 'Account '+this.accountName+'Created Successfully!!',
            variant: 'success'
        });
        this.dispatchEvent(toastEvent);    
      
    }
   
}


meta file:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>
            lightning__AppPage
        </target>
        <target>
            lightning__HomePage
        </target>
    </targets>
</LightningComponentBundle>



Reference:

No comments:

Post a Comment

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...