Calling Apex method from another Apex method callback in Salesforce Lightning

Sample Code:

Lightning Component:

<aura:component implements="force:appHostable"
                controller="Sample">

    <div class="slds-box slds-theme_default">
<lightning:button variant="brand" label="Click" onclick="{!c.call1}"/>        
    </div>
    

</aura:component>

Lightning Component Controller:

({
call1 : function(component, event, helper) {
var action = component.get("c.firstMethod");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                if ( response.getReturnValue() === 'error' ) {
                    $A.enqueueAction(component.get('c.call2'));
                }
            }
        });
        $A.enqueueAction(action);
},
    call2 : function(component, event, helper) {
        var action = component.get("c.secondMethod");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                alert(response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }

})

Apex Class:

public class Sample {

    @AuraEnabled
    public static String firstMethod() {
        return 'error';
    }
    
    @AuraEnabled
    public static String secondMethod() {
        return 'Success';
    }
    

}

Output:


No comments:

Post a Comment