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
- In VS Code, edit
notificationConsole.js
. - Add the following line to the top of the file to import the
lightning/empApi
module: Thelightning/empApi
module provides methods to subscribe and unsubscribe to platform events and change data capture events. - Add a new class method with the following code (you can add it before the final closing curly bracket):
handleNotificationEvent
method to parse our custom Notification platform event and update the user interface.
Use this - Replace the body of the
connectedCallback()
method with the following code: 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 newNotification__e
events. - The subscription information in the
subscription
class attribute is saved so that you can use it to unsubscribe later.
- A default error handler for EMP API is created thanks to the
- Add a new class method with the following code (add it before the final closing curly bracket):
- The
disconnectedCallback()
LWC lifecycle hook method is used to unsubscribe from the EMP API when the component is removed from the page.
Code Highlights:
- The
- Save the file.
- Right click on the lwc folder and select SFDX: Deploy Source to Org to redeploy your updated component to your org.
- 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.
- Open the Bear Watch Heroku app.
- Click Log In.
- When you are prompted to allow access to the Bear Watch application, click Allow.
- 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.
- Click Broadcast bear warning.
A "Watch out, bear spotted!" notification appears in the Salesforce window.