3

I am new to angularjs.After creating some projects with restful web service I got stuck at some point.So please help to me to solve that issues. I have read the difference between $resource and $http from AngularJs $resource vs $http

My issue is that as I am using $resource the data come asynchronously e.g. if I am saving any data and transfer to detail page that data I got is not updated and if I will wait for some time than I will get newly data.

So I need to go on $http or is there any other way to make call synchronously. I have also try with $promise but it doesn't solve my issue.

Community
  • 1
  • 1
Chintan
  • 59
  • 1
  • 8

1 Answers1

4

This is how I use $resource

in controller:

var promise = Service.queryItem();
    promise.then(function(response){

        // just adding my response items to an array
        angular.forEach(response, function(item){
            $scope.items.push(item);
        });

    }, function(reason){
        console.log(reason);
});

In service

this.queryItem = function (){

    var deferred = $q.defer();
    setTimeout(function() {
        // deferred.notify('Saving data..');
        var items = Items.query({},function() {
            deferred.resolve(items.d.results);
        }, function(error){
            deferred.reject(error);
        });
    }, 1000);
    return deferred.promise;
};

In $resource factory:

// just a snippet from my factory
query: {
    method: 'GET',
    headers: { "Accept": "application/json; odata=verbose" },
    url: "RequestURL"
},

As some comments stated, the use of promise will make it run in the desired order , as you can see I do my forEach after .then

sch
  • 1,368
  • 3
  • 19
  • 35