Lightning Messaging Service: It is used to communicate between the visualforce pages, aura components and Lightning web Components. It can be used to communicate between one aura component and one Lightning web component as well and also between one visualforce page and one aura component as well.
Example: In this example you can see how a message is communicated from one lightning web component to other lightning web componentStep 1: Create a lightning messaging channel: Go to visual studio code tool and create 'messageChannels' folder inside the default folder as shown in image below
create a file as 'filename.messageChannel-meta.xml' shown in the image below and deploy to salesforce org.
Step 2: Create publisher lightning web component(source)
publisherLWCComponent.html:
<template>
<lightning-card>
<div class="slds-grid">
<lightning-button label="Publish" variant="brand" onclick={sendMessage}></lightning-button>
</div>
</lightning-card>
</template>
publisherLWCComponent.js:
import { LightningElement } from 'lwc';
import { createMessageContext, releaseMessageContext,publish} from 'lightning/messageService';
import msg from "@salesforce/messageChannel/TestMessageChannel__c";
export default class PublisherLWCComponent extends LightningElement {
context = createMessageContext();
sendMessage() {
const msgTosend = {
paramOne: 'This is message to be sent to other LWC'
}
publish(this.context, msg, msgTosend);
};
}
publisherLWCComponent.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Step3: Create Subscriber Lightning web component(destimation):
subscriberLWCComponent.html:
<template>
<lightning-card>
Message Received: {msgReceived}
</lightning-card>
</template>
subscriberLWCComponent.js:
import { LightningElement,track } from 'lwc';
import { createMessageContext, releaseMessageContext,APPLICATION_SCOPE,subscribe, unsubscribe } from 'lightning/messageService';
import msg from "@salesforce/messageChannel/TestMessageChannel__c";
export default class SubscriberLWCComponent extends LightningElement {
context = createMessageContext();
@track msgReceived ='';
connectedCallback(){
subscribe(this.context, msg, (message) => {
this.msgReceived = message.paramOne;
},{scope: APPLICATION_SCOPE});
}
}
subscriberLWCComponent.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
No comments:
Post a Comment