Lightning Simple Apex Method Call:

This lesson teaches about how to access backend from apex into lightning component

The example shows Lightning component with an attribute
The attribute is set onclick of button ,which gets the call from apex method

Key point to note here :
The lightning component has controller ="Controller Name" during declaration
Only the methods in that particular class are accessable to the lightning component
Below is the sample program for the same
apex :
Create and copy paste the apex class and name it as HelloWorldApexMethod
/*


 * created by 		:		Shiva RV
 * Date				:		13-10-2018
 * Description		:		ApexMethodHelloWorld component
  
*/
public class HelloWorldApexMethod {
 @AuraEnabled
    public static String sayHelloString()
    {
        return 'Hello World';
    }
    
}
Create a lightning component with the below markup code and name the component as
ApexMethodSimpleHelloWorld:
<!--


 * created by 		:		Shiva RV
 * Date				:		13-10-2018
 * Description		:		Component to show various return type usage from apex
  
-->
<aura:component controller="HelloWorldApexMethod">
   
    <aura:attribute name="StringData" type="String"></aura:attribute>
	
	<div class="slds-button-group" role="group">
  	<lightning:button label="fetch String" name="fetch String" aura:id="fetchString" onclick="{!c.fetchString}"></lightning:button> 
  	
	</div>
    <br/>
    Your input from apex is {!v.StringData}
</aura:component>
 Js controller code :
({
	fetchString : function(component, event, helper) {
		helper.fetchStringHelper(component);
	}
})
Helper :
({
	fetchStringHelper : function(component) {
	 var action = component.get("c.sayHelloString");
         action.setParams({});
         action.setCallback(this, function(response)
         {
         	var state = response.getState();
         	if (state === "SUCCESS") 
         	{
               component.set("v.StringData",response.getReturnValue());
         	}
         	else
         	{
                // do something
         	}    
         });
         $A.enqueueAction(action);	
	}
})
Below is the hello world App code:
<!--


 * created by 		:		Shiva RV
 * Date				:		13-10-2018
 * Description		:		Hello World Lighting App
  
-->

<aura:application extends="force:slds">
<!--this is the lightning app where you can place html codes , associate js code
		also can embed lightning component to it -->
  
  <!-- simple action apex method demo -->
    <c:ApexMethodSimpleHelloWorld></c:ApexMethodSimpleHelloWorld>

</aura:application>
Output:

 

Key Notes :
*Note apex action is called asynchronously in lightning
*Notice the action in helper, it's a good practise to have the apex action or any resuable code in helper
*An action requires method name ,setparams to set the parameters to pass , setcallback will be called asyncronously
*Notice the $A.enqueueAction() , that makes the apex call to happen from js
*Only @AuraEnabled Methods are accessible in lightning