Saleforce Apex与LWC的通信

45 阅读1分钟

在标准的页面编辑记录后,如果需要在页面弹窗特殊的信息,比如:线索更新后,触发器执行特殊的查重,有重复的需要提醒用户。

可以借助上一篇文章引入的空白LWC作为辅助,Apex与LWC的通信借助的是平台事件(Platform Events)

1.新建平台事件:

image.png

2.LWC订阅事件:

import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from 'lightning/empApi';

export default class BlankRecordPage extends LightningElement {
    subscriptionPlatform = {};  
    @api channelName = '/event/LeadDuplicat__e';

    connectedCallback() {  
        ......
        this.registerErrorListener();  
        this.handleSubscribe();  
    }
    
    registerErrorListener() {  
        onError(error => {  
            console.log('Received error from server: ', JSON.stringify(error));  
        });  
    }
    
    handleSubscribe() {  
        subscribe(this.channelName, -1, (response) => {
            console.log('event response ===> ', response);  
            let obj = JSON.parse(JSON.stringify(response));  
            let res = obj.data.payload;  
            if (res.LeadId__c == this.recordId) {  
                // ... 执行弹窗信息逻辑
            } 
        }).then(response => {  
            this.subscription = response;  
        });  
    }
}

3.Apex发布事件

List<LeadDuplicat__e> msgList = new List<LeadDuplicat__e>();
LeadDuplicat__e message = new LeadDuplicat__e();  
msgList.add(message);  
message.LeadId__c = 'xxx';
EventBus.publish(msgList);

参考文章:Platform Events Developer GuidePlatform Events in LWC Salesforce