Search code examples
javascriptampersand.jsampersand-collection

ampersand fetch data from rest api


I create collection with ampersand-rest-collection like this :

module.exports= AmpersandRestCollection.extend({
    url: 'http://www.mocky.io/v2/58b42441110000011c1c43bf',
    mainIndex: '_id',
    indexes: ['otherId'],
    model:ProvincesModel
});

and use it like this :

let provinces = new ProvinceRestCollection();

        provinces.fetch();

        provinces.each(function(model){
        console.log("model : "+model);
    })

and response json data like this :

  [
    { _id: 1, otherId: 'a', name: 'Phil' },
    { _id: 2, otherId: 'b', name: 'Julie' },
    { _id: 3, otherId: 'c', name: 'Henrik' },
    { _id: 4, otherId: 'd', name: 'Jenn' }
]

App send GET request to rest service and receive json data in response successfuly ,but provinces collection is empty!!!

How can I use response data after fetch() method ????


Solution

  • Ampersand.js (and every js library) fetches the data in an asynchronous way. That said, you can only access the items when the operation finished, the framework usually notifies you by a callback function. In ampersand you have to do something like this:

    let provinces = new ProvinceRestCollection();
    
    provinces.fetch({
        success: function() {
            provinces.each(function(model) {
                console.log("model : " + model);
            });
        }
    });