Lightning Message Service in Aura Components: The Essential Guide

Unlock the potential of Salesforce with the Lightning Message Service (LMS). Dive into our guide to optimize inter-component communication in Aura components for a seamless user experience.

Introduction

In the vast universe of Salesforce, there's a shining star that stands out for bridging communication gaps: the Lightning Message Service (LMS). Specifically designed to enable inter-component communication, LMS is crucial for both Aura and Lightning Web Components. In this guide, we will delve deep into implementing LMS within Aura components, ensuring your Salesforce applications are seamless, effective, and user-friendly.


What is Lightning Message Service?

The Lightning Message Service is a Salesforce feature that facilitates communication between Aura, Lightning Web Components (LWC), and Visualforce pages. Whether you're toggling between components or seeking to update several at once, LMS makes these tasks effortless.


Why is LMS Essential for Aura Components?

  1. Unified Communication: LMS provides a common platform for different component types to converse, breaking the barriers that existed between Aura and LWC.
  2. User Experience: With seamless interactivity, users find the application more responsive and intuitive.
  3. Avoid Redundancy: By reducing the need for similar code in multiple components, LMS promotes DRY (Don't Repeat Yourself) principles.
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.

How to Implement LMS in Aura Components?

  1. Import the Required Modules: Begin by importing the necessary modules. Typically, this involves referencing the lightning/messageService and your specific message channel.
  2. Subscribe to a Channel: Utilize the messageService.subscribe() method. This allows your Aura component to listen for specific messages.
  3. Send a Message: When you want to broadcast information to other components, use the messageService.publish() method.
  4. Unsubscribe: To prevent memory leaks and ensure optimal performance, remember to unsubscribe from channels when they are no longer needed using messageService.unsubscribe().

Best Practices for Implementing LMS in Aura Components:

  1. Granular Channels: Instead of one broad channel, consider segmenting your messages. This ensures only relevant components respond, enhancing efficiency.
  2. Clear Naming Conventions: Name your channels descriptively to avoid confusion and maintain readability.
  3. Robust Error Handling: Always incorporate error handling, especially when dealing with cross-component communication.

Let us look at the code snippet!

💡
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.
  1. Create a Lightning Message Channel:

This has to be created using Visual Studio Code and we cannot create it from the Salesforce Org. We need to specify the MessageChannelName as well as LightningMessageFields using which we want to transfer the data.

<?xml version="1.0" encoding="UTF-8" ?>
<LightningMessageChannel>
    <masterLabel>AccountData</masterLabel>
    <isExposed>true</isExposed>

    <description
  >This is a channel which is used by LWC component to send data</description>
        <!-- Am creating two fields that will be eventually 
        used to send data -->
    <lightningMessageFields>
        <description>This is the Id of the record</description>
        <fieldName>recordId</fieldName>
    </lightningMessageFields>
    <lightningMessageFields>
        <description>This is the  of the record</description>
        <fieldName>name</fieldName>
    </lightningMessageFields>
</LightningMessageChannel>
AccountMessageChannel.messageChannel-meta.xml

2.  Create a Publisher:

The complete flow starts with a Publisher publishing the data and placing the data on the Lightning Message Channel.

<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

3.  Publish the data:

This is the controller of the publishing Aura Component that is used to publish the data.

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

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

4.  Create a Subscriber:

Here is the Aura Component that subscribes to the message channel and receives data using Lightning Messaging Service.

<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

5.  Extract the data out of the Message Channel:

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

Conclusion:

The Lightning Message Service is a pivotal tool in the Salesforce developer's toolkit. When integrated into Aura components, it paves the way for dynamic and responsive applications that can easily adapt to user needs. By adhering to best practices, you ensure not just functional, but also efficient and maintainable Salesforce solutions.