Using v.recordId with Apex Class to Query Data

DEX601 - Unit 4 Surfacing Aura Components

📄 第 304 页 🎬 视频课程

课程章节介绍

让我们一步一步来理解这段代码。首先,这段代码的目的是在Salesforce的Lightning组件中,使用Apex类来查询特定联系人的数据。我们有两个主要部分:Lightning组件的JavaScript控制器和Apex类。 ### 1. Lightning组件的JavaScript控制器 ```javascript ({ doInit: function(component, event, helper) { helper.callServer( component, "c.getContactData", function(response) { console.log(response); }, { contactId: component.get('v.recordId') } ); } }) ``` - ,doInit,: 这是一个初始化函数,当组件加载时会自动调用。 - ,helper.callServer,: 这是一个辅助函数,用于调用服务器端的Apex方法。 - ,component,: 当前组件的引用。 - ,"c.getContactData",: 这是我们要调用的Apex方法的名称。 - ,function(response),: 这是一个回调函数,当Apex方法返回数据时,这个函数会被调用,并且`response`参数会包含返回的数据。 - ,{ contactId: component.get('v.recordId') },: 这是传递给Apex方法的参数。`component.get('v.recordId')`获取当前组件的`recordId`属性值,并将其作为`contactId`参数传递给Apex方法。 ### 2. Apex类 ```apex public with sharing class MyController { @AuraEnabled public static Contact getContactData(Id contactId) { return [SELECT Id, Phone FROM Contact WHERE Id = :contactId]; } } ``` - ,public with sharing class MyController,: 这是一个Apex类,`with sharing`表示这个类遵循用户的权限设置。 - ,@AuraEnabled,: 这个注解表示这个方法可以被Lightning组件调用。 - ,public static Contact getContactData(Id contactId),: 这是一个静态方法,返回一个`Contact`对象。它接受一个`Id`类型的参数`contactId`。 - ,return [SELECT Id, Phone FROM Contact WHERE Id = :contactId];,: 这是一个SOQL查询,根据传入的`contactId`查询对应的联系人记录,并返回`Id`和`Phone`字段。 ### 3. 总结 - ,Lightning组件,:当组件加载时,`doInit`函数会被调用,它会通过`helper.callServer`调用Apex方法`getContactData`,并将当前组件的`recordId`作为参数传递。 - ,Apex类,:`getContactData`方法接收`contactId`参数,并查询对应的联系人记录,返回`Id`和`Phone`字段。 这样,当组件加载时,它会自动查询并显示与`recordId`对应的联系人的`Id`和`Phone`信息。 希望这个解释对你有帮助!如果有任何问题,随时问我。