In the previous post, we looked at how to use LMS in LWC to send data. In this post, we will look at how to send data from one Aura Component to another Aura Component using LMS.

We can do it using Application Events too. However, with LMS the implementation is a lot easier and it can be used with Aura and Visualforce too.

We need to create a message channel and we will not be looking at creating the messsge channel as we have seen in it in this post.

Let us look at the code snippet!

This is the Aura Component that will be publishing the data using LMS.

<aura:component
  implements="force:hasRecordId,flexipage:availableForAllPageTypes,
  flexipage:availableForRecordHome"
>
  <aura:attribute name="recordId" type="String" />
  <lightning:button
    label="Send Payload"
    variant="brand"
    onclick="{! c.handleClick }"
  />
  <lightning:messageChannel
    type="AccountDataMessageChannel__c"
    aura:id="sampleMessageChannel"
  />
</aura:component>
publisher.cmp

This is the controller of the publishing Aura Component.

({
  handleClick: function (component, event, helper) {
    let rId = component.get("v.recordId");
    var payload = {
      recordId: rId,
      name: "Teja"
    };

    component.find("sampleMessageChannel").publish(payload);
  }
});
publisherController.js

Here is the Aura Component that subscribes to the message channel and receives data using LMS.

<aura:component
  implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome"
>
  <aura:attribute name="recordValue" type="String" />

  <lightning:messageChannel
    type="AccountDataMessageChannel__c"
    onMessage="{!c.handleMessage}"
  />

  <lightning:input value="{!v.recordValue}"></lightning:input>
</aura:component>
subscriber.cmp

This is the controller file of the subscribing Aura Component.

({
  handleMessage: function(cmp, event, helper) {
    // Read the message argument to get the values in the message payload
    if (event != null && event.getParams() != null) {
      let params = event.getParams();
      cmp.set("v.recordValue", JSON.stringify(params, null, "\t"));
    }
  }
});
subscriberController.js

Hope this is helpful!