Bringing Data From REST to Your Salesforce Lightning Component Part 2
In the last lesson we built a very basic record home component. In this lesson we’ll add some data we’re receiving from Apex and display it in the component. We’ve previously shown how you can integrate with a third party. I’ve adapted Mike’s example into a WeatherUtil class that pulls from Weather Underground (you’ll need your own API key, dev keys are free).
One of they key things added into the class are the static methods with the @AuraEnabled annotation. We’ll be using the getLocalWeatherByRecord method to get the weather for our Account records.
WeatherUtil (Apex class)
In our component we’ll need to add the controller=”WeatherUtil” to let the component know we’ll be using the WeatherUtil class as a backend Apex class. We also need an attribute to hold the weather data in, and some DOM to present the weather data.
In our client side JS controller we need to add some code to our initial method to call a helper method that will communicate with the Apex backend utility class. The showDetails method is used to show extra hidden data about the weather.
In the helper we add a method to get the local weather, and a layout method that will take our results and properly handle them.
After you save your component, open an Account that has ShippingCity and ShippingState populated to see the results. If you didn’t add the component in the first lesson, add the component to a record home lightning page, then save and activate to see the results.
Easier Record Home Component Testing
Sometimes testing a component within Lightning Experience can be a hassle. I’ve found refreshing can be a bit awkward due to some caching they’re doing. Getting the latest version of your component to show immediately isn’t as simple as opening the record again. To combat this I’ve put my component into a custom app during development so I can more easily refresh.
It’s a simple process to imitate a record home component living in LEX. First create a new Lightning Application inside the dev console (or your respective Lightning capable IDE). Inside the Lightning Application body make your record component and pass it a recordId and sObjectName (if applicable).
To match the styling of the Lightning Design System since a custom application doesn’t have it automatically loaded like Lightning Experience does, add a static resource version of it with ltng:require.
I added some width and margin styling to make it similar to the panel it’d live in on the record home layout. This isn’t required but is helpful in seeing what it would actually look like.
Now browse to /c/yourapp.app and you’ll be able to see the component as it would appear on the record home.
If your company or nonprofit is interested in taking your Salesforce org into the Lightning era, contact us: