1

I'm using Lightning message service to pass message from LWC to another LWC.Both components are custom components used in community pages. The message is not being sent to the other component.

Publisher

import { publish, MessageContext } from 'lightning/messageService';
import SCORING from '@salesforce/messageChannel/Scoring__c';
    @wire(MessageContext)
    messageContext;
    msgTest = 'test';

    publishMeasureItems() {
            const payload = { measureItems: this.msgTest };
    
            publish(this.messageContext, SCORING, payload);
        }
    connectedCallback(){
        publishMeasureItems();
    }

Subscriber

@wire(MessageContext)
    messageContext;

    subscription = null;
    measureItems = [];

    // Navigate to fiche nutrition after clicking on back arrow 
    handleArrowClick() {
        this[NavigationMixin.Navigate]({
            type: 'comm__namedPage',
            attributes: {
                name: 'Programme__c'
            },
        });
    }

    // Encapsulate logic for Lightning message service subscribe and unsubsubscribe
    subscribeToMessageChannel() {
        if (!this.subscription) {
            this.subscription = subscribe(
                this.messageContext,
                SCORING,
                (message) => this.handleMessage(message),
                { scope: APPLICATION_SCOPE }
            );
        }
    }

    unsubscribeToMessageChannel() {
        unsubscribe(this.subscription);
        this.subscription = null;
    }

    // Handler for message received by component
    handleMessage(message) {
        this.measureItems = message.measureItems;
    }

    // Standard lifecycle hooks used to subscribe and unsubsubscribe to the message channel
    connectedCallback() {
        try {
            this.subscribeToMessageChannel();
            console.log('######################' + this.measureItems);
        } catch (error) {
            console.log(error);
        }
    }

    disconnectedCallback() {
        this.unsubscribeToMessageChannel();
    }

1 Answer 1

2

The problem was that the components are on different pages. In this case the messaging would not work as it is explained in this Q&A:

Lightning Message Service doesn't work between community pages

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .