Wednesday, 4 January 2023

How do you use Lightning Aura components to interact with Apex classes?

To use Lightning Aura components to interact with Apex classes, you can use the @AuraEnabled annotation in your Apex class to expose the class and its methods to Lightning Aura components. You can then use the Lightning Aura component's JavaScript controller to call the Apex class method using the Lightning Data Service (LDS) or the Lightning Component Library (LCL).

Here is an example of an Apex class with an @AuraEnabled method:

public with sharing class MyApexClass {

    @AuraEnabled

    public static String getMessage() {

        return 'Hello from Apex';

    }

}

And here is an example of a Lightning Aura component that calls the Apex class method using LDS:

<!-- myComponent.cmp -->

<aura:component>

    <aura:attribute name="message" type="String" />

    <lightning:button label="Get Message" onclick="{! c.getMessage }" />

    <br />

    <p>{! v.message }</p>

</aura:component>


// myComponentController.js

({

    getMessage: function(component, event, helper) {

        // Call the Apex class method

        var action = component.get('c.getMessage');


        // Set the callback function

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === 'SUCCESS') {

                // Set the component attribute with the returned value

                component.set('v.message', response.getReturnValue());

            } else {

                console.log('Error: ' + state);

            }

        });


        // Send the request to the server

        $A.enqueueAction(action);

    }

})

I hope this helps! 

No comments:

Post a Comment