Introduction

The main concept included in this recipe is subscribing to a message channel, that has been previously created here LWC LmsPublisherWebComponent.

Subscriber component

This LWC subscribes to the messages sent into a message channel named Record_Selected__c.

The payload message in this channel is a contact recordId. Once the record Id is received, a wire is used to retrieve the contact details such as the name, title, phone, email and the picture.

On this page, the focus will be on the part referencing the subscribing to the message, as there are other LWCs in the cookbook that already explain how to use a wire adapter.

<aside> 💡 If you are not familiar with Lightning Message Service, review this section before digging into this LWC: Introduction.

</aside>

<aside> 📂 Find this LWC in this folder: force-app/main/default/lwc/lmsSubscriberWebComponent

</aside>

Importing the message channel

This is the first step to be able to subscribe to the channel:

  1. Import the subscribeand MessageContextAPIs required.
  2. Import the message channel definition.
// Import message service features required for subscribing and the message channel
import { subscribe, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED_CHANNEL from '@salesforce/messageChannel/Record_Selected__c';

Subscribing to the message channel

To subscribe to the message channel:

  1. Invoke the wire adapter to obtain the Message Context
  2. Invoke the subscribemethod providing, the Message Context, the imported message channel name and a handler to manage the payload when a message is received
  3. The subscription is done in the connectedCallback lifecycle step, when the LWC will be added to them DOM

It is important to notice several topics:

  1. That the scope used is active, as there is no explicit mention to the application one.