Skip to main content
Build the future with Agentforce at TDX in San Francisco or on Salesforce+ on March 5–6. Register now.
Estimación de tiempo

Subscribe to a Platform Event

Next, you extend the Lightning console app and add the lightning/empApi module to subscribe to a platform event. This enables the app to receive instant notifications. Then you can test the application with a Heroku app.

Update the Component

  1. In VS Code, edit notificationConsole.js.
  2. Add the following line to the top of the file to import the lightning/empApi module:
    import { subscribe, unsubscribe, onError } from "lightning/empApi";
    The lightning/empApi module provides methods to subscribe and unsubscribe to platform events and change data capture events.
  3. Add a new class method with the following code (you can add it before the final closing curly bracket):
    handleNotificationEvent(event) {
      console.dir(event);
      // Parse event data
      const id = event.data.event.replayId;
      const message = event.data.payload.Message__c;
      const utcDate = new Date(event.data.payload.CreatedDate);
      const time = `${utcDate.getMinutes()}:${utcDate.getSeconds()}`;
      // Add notification to view
      const notification = {
        id,
        message,
        time
      };
      this.notifications.push(notification);
      // Show notification message as a toast
      this.dispatchEvent(
        new ShowToastEvent({
          variant: "info",
          title: message
        })
      );
    }
    Use this handleNotificationEvent method to parse our custom Notification platform event and update the user interface.
  4. Replace the body of the connectedCallback() method with the following code:
    // Configure default error handler for the EMP API
    onError((error) => {
      this.dispatchEvent(
        new ShowToastEvent({
          variant: "error",
          title: "EMP API Error",
          message: "Check your browser's developer console for more details."
        })
      );
      console.log("EMP API error reported by server: ", JSON.stringify(error));
    });
    // Subscribe to our notification platform event with the EMP API
    // listen to all new events
    // and handle them with handleNotificationEvent
    this.subscription = await subscribe(
      "/event/Notification__e",
      -1,
      (event) => this.handleNotificationEvent(event)
    );
    // Display a toast to inform the user that we're ready to receive notifications
    this.dispatchEvent(
      new ShowToastEvent({
        variant: "success",
        title: "Ready to receive notifications"
      })
    );
    Code Highlights:

    • A default error handler for EMP API is created thanks to the empApi.onError() method. This allows us to report streaming errors as a toast notification and in the browser's dev console.
    • The asynchronous empApi.subscribe() method is called to subscribe to all new Notification__e events.
    • The subscription information in the subscription class attribute is saved so that you can use it to unsubscribe later.
  5. Add a new class method with the following code (add it before the final closing curly bracket):
    disconnectedCallback() {
      // Unsubscribe from EMP API
      unsubscribe(this.subscription);
    }
    Code Highlights:

    • The disconnectedCallback() LWC lifecycle hook method is used to unsubscribe from the EMP API when the component is removed from the page.
  6. Save the file.
  7. Right click on the lwc folder and select SFDX: Deploy Source to Org to redeploy your updated component to your org.
  8. Back in the Sales app, refresh your browser window to load the updates you made to the notification console. Make sure that there are no errors displayed.

Test the Instant Notification App

To test the instant notification app, you use an external application, the Bear Watch Heroku app.

  1. Open the Bear Watch Heroku app.
  2. Click Log In.
  3. When you are prompted to allow access to the Bear Watch application, click AllowAccess authorization prompt for the Bear Watch application.
  4. Resize and position your browser windows so that you can see both your Salesforce Sales app and the Bear Watch app at the same time. You might have to refresh the home page of the Sales app to receive new notifications.
  5. Click Broadcast bear warning.

A "Watch out, bear spotted!" notification appears in the Salesforce window.

An image showing a notification being sent from the Bear Watch Heroku application and received in the notification console in Salesforce

Comparta sus comentarios sobre Trailhead en la Ayuda de Salesforce.

Nos encantaría conocer su experiencia con Trailhead. Ahora puede acceder al nuevo formulario de comentarios cuando quiera desde el sitio de la Ayuda de Salesforce.

Más información Continuar para compartir comentarios