Consuming REST calls in Lightning Component
Component Usage Demo
Component : Glossary.cmp
<aura:component controller="GlossaryService" implements="force:appHostable,flexipage:availableForAllPageTypes" >
<lightning:card title="SFDC Glossary" iconName="standard:account" footer="Powered by Glossary Service">
<aura:set attribute="actions"> </aura:set>
<p class="slds-p-horizontal_small">
<lightning:input
aura:id="searchInput"
type="search" label="Search" placeholder="Enter search term"
onchange="{!c.searchInputChange}"/>
<ui:inputTextarea value="results here..." aura:id="searchOutput" cols="200" rows="20">
</ui:inputTextarea>
</p>
</lightning:card>
</aura:component>
Server-side controller : GlossaryService.apxc
public class GlossaryService {
@AuraEnabled
public static String getMeaning(String term) {
Http http = new Http();
HttpRequest request = new HttpRequest();
String url = 'https://mohansun-canvas-chartapp2.herokuapp.com/search/sfdc/'+ term;
request.setEndpoint(url);
request.setMethod('GET');
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
return response.getBody();
}
return '[]';
}
}
Client-side controller: GlossaryController.js
({
searchInputChange : function(component, event, helper) {
var input = component.find("searchInput")
var valueGot = input.get("v.value");
var action = component.get("c.getMeaning");
action.setParams({ term : valueGot} );
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var resultOutput = response.getReturnValue();
var output = component.find("searchOutput");
var outputObj = JSON.parse(resultOutput) ;
output.set("v.value", JSON.stringify(outputObj, null, 4));
}
else if (state === "INCOMPLETE") {
}
else if (state === "ERROR") {
var errors = response.getError();
if (errors) {
if (errors[0] && errors[0].message) {
console.log("Error message: " +
errors[0].message);
}
} else {
console.log("Unknown error");
}
}
});
$A.enqueueAction(action);
}
})
Testing App: TestingApp.app
<aura:application extends="force:slds" >
<c:Glossary/>
</aura:application>
Component Usage in Lightning Page Demo