Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does angular $resource add extra objects ($promise, $resolve...) to my data response?

I return a resource with a URL

    $resource("http://foo.com/bar.json").get().
         $promise.then(function(data){ $scope.result = data}, 
                  function(error){ $scope.msg = "error" } );

Resource returns

["item1"...."item_n",.....,"$promise", "$resolved", "$get", "$save", "$query", "$remove", "$delete"]

Why do I get all those objects in my data set. I'm guessing $promise just returns all this and waits for the server response. But once I have the server response where can I just get my server data without the Promise jargon?

like image 537
EKet Avatar asked Mar 21 '14 00:03

EKet


People also ask

What is $resource in AngularJS?

Overview. A factory which creates a resource object that lets you interact with RESTful server-side data sources. The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service. Requires the ngResource module to be installed.

What is q defer()?

$q. defer() allows you to create a promise object which you might want to return to the function that called your login function.

What is promise in AngularJS?

Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. {info} Promises have made their way into native JavaScript as part of the ES6 specification.

What is$ q in angular?

Using angular promises with $q service. $q is a built-in service which helps in executing asynchronous functions and using their return values(or exception) when they are finished with processing. $q is integrated with the $rootScope.


2 Answers

If you look at the angular source here:

https://github.com/angular/angular.js/blob/master/src/ngResource/resource.js#L505

There is a toJSON method on the Resource prototype chain that will accomplish this for you.

For example:

$resource("http://foo.com/bar.json").get(function(res) {
    $scope.result = res.toJSON();
});
like image 85
raygerrard Avatar answered Sep 16 '22 19:09

raygerrard


You need to return wrapped result like {'result': { 'some_key': 'some_val' }} from your backend. Or just do like described above.

Diary.getSharedWithMe(function(data) {
        delete data.$promise;
        delete data.$resolved;
        _self.sharedDiariesWithMe = data;
    }, function(error) {
        console.log(error)
    });
like image 27
callmejuggernaut Avatar answered Sep 16 '22 19:09

callmejuggernaut