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.

4
  • Code? Using promises should be a viable way to solve it. Commented Dec 1, 2015 at 14:14
  • I doubt the answer is to do a sync request - can you post your code in question? Commented Dec 1, 2015 at 14:14
  • You don't want synchronous data, your UI will be stuck and it's deprecated. Commented Dec 1, 2015 at 14:26
  • Do all your manipulation part inside the promise returned by the API i.e in success response Commented Dec 1, 2015 at 14:29

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.