4

I've been trying to make a request to a NodeJS API. For the client, I am using the Mithril framework. I used their first example to make the request and obtain data:

var Model = {
    getAll: function() {
        return m.request({method: "GET", url: "http://localhost:3000/store/all"});
    }
};

var Component = {
    controller: function() {
        var stores = Model.getAll();

        alert(stores); // The alert box shows exactly this: function (){return arguments.length&&(a=arguments[0]),a}
        alert(stores()); // Alert box: undefined
    },
    view: function(controller) {
        ...
    }
};

After running this I noticed through Chrome Developer Tools that the API is responding correctly with the following:

[{"name":"Mike"},{"name":"Zeza"}]

I can't find a way to obtain this data into the controller. They mentioned that using this method, the var may hold undefined until the request is completed, so I followed the next example by adding:

var stores = m.prop([]);

Before the model and changing the request to:

return m.request({method: "GET", url: "http://localhost:3000/store/all"}).then(stores);

I might be doing something wrong because I get the same result.

The objective is to get the data from the response and send it to the view to iterate.

mignz
  • 3,648
  • 2
  • 20
  • 21

1 Answers1

2

Explanation:

m.request is a function, m.request.then() too, that is why "store" value is:

"function (){return arguments.length&&(a=arguments[0]),a}"

"stores()" is undefined, because you do an async ajax request, so you cannot get the result immediately, need to wait a bit. If you try to run "stores()" after some delay, your data will be there. That is why you basically need promises("then" feature). Function that is passed as a parameter of "then(param)" is executed when response is ready.

Working sample:

You can start playing with this sample, and implement what you need:

var Model = {
    getAll: function() {
        return m.request({method: "GET", url: "http://www.w3schools.com/angular/customers.php"});
    }
};

var Component = {

    controller: function() {
        var records = Model.getAll();

        return {
            records: records
        }
    },

    view: function(ctrl) {
        return m("div", [
            ctrl.records().records.map(function(record) {
                return m("div", record.Name);
            })
        ]);
    }
};

m.mount(document.body, Component);

If you have more questions, feel free to ask here.

Ross Khanas
  • 1,491
  • 2
  • 15
  • 23
  • Found out that storing the value as `this.records` in the controller, without a return also works. Thanks for your response. – mignz Nov 23 '15 at 17:21