9

I am attempting to set the value of a lightning component attribute with the type JSON to the contents of a JSON static resource file. I am using the following to set the attribute from the client side controller.

cmp.set('v.attribute', $A.get('$Resource.StaticResourceName'));

This, however, is producing the file path string, not the data itself. I have checked How does one access the file contents themselves to set it to a variable?

3 Answers 3

10

You can get the data with a simple HTTP request:

({
    init: function(component, event, helper) {
        var path = $A.get("$Resource.StaticResourceName");
        var req = new XMLHttpRequest();
        req.open("GET", path);
        req.addEventListener("load", $A.getCallback(function() {
            component.set("v.attribute", req.response);
        }));
        req.send(null);
    }
})
0
6

I would like to share an alternative approach by using Fetch API (MDN web docs)

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.

For making a request and fetching a resource, use the WindowOrWorkerGlobalScope.fetch() method. It is implemented in multiple interfaces, specifically Window and WorkerGlobalScope. This makes it available in pretty much any context you might want to fetch resources in.

So, you can get the content of your JSON file from the static resource next way:

{(
    onInit: function (component, event, helper) {
        const url = new URL(window.location.href);
        const resourceRelPath = $A.get('$Resource.StaticResourceName');
        const resourceUrl = `${url.origin}${resourceRelPath}`;
        window.fetch(resourceUrl)
            .then($A.getCallback((response) => {
                if (!response.ok) {
                    throw new Error(`HTTP error, status = ${response.status}`);
                }
                response.json()
                    .then($A.getCallback((data) => {
                        component.set('v.yourAttribute', data);
                    }));
            }))
            .catch($A.getCallback((error) => {
                console.error('Fetch Error :-S', error);
            }));
    },
)};

Or you can query it via Apex Controller:

public with sharing class StaticResourceController {
    @AuraEnabled
    public static String getStaticResContentByName(String name) {
        Blob jsonContentAsBlob = [
                                   SELECT Body 
                                   FROM StaticResource 
                                   WHERE Name = :name
                                 ].Body;
        return jsonContentAsBlob.toString();
    };

PS. Using this approach don't forget to parse a response body using JSON.parse() function within Lightning Controller.

3
  • 2
    +1 Learned something new today! The only downside at the moment is that IE 11 doesn't support it, but our org hasn't migrated to Edge/Firefox fully as of yet, but I'm going to remember this for the future.
    – sfdcfox
    Commented Apr 17, 2019 at 20:17
  • 3
    It's nice to hear from the living legend. We are all gathered here to share knowledge and experience or ask an interesting question. For this, we all love Stack Exchange.))) Commented Apr 17, 2019 at 20:48
  • Thanks for sharing these additional ways of accessing static resource data. This has helped me to realise that the issue here was not necessarily that Lightning doesn't give you the option of retrieving the file contents, but that the method to retrieve that information is instead available via standard javascript functionality and even from APEX as you point out. Cheers!
    – dannymorty
    Commented Apr 23, 2019 at 10:48
0

Adding to @sfdcfox 's answer, i had to dig into the response. In my case the static resource was an image, hence responseUrl was the parameter to be set in the set attribute method at the end

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .