Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS using $resource service. Promise is not resolved by GET request

Tags:

json

angularjs

Let's say a service like this:

   services.factory('User', function($resource){         return $resource('/rest/usersettings/:username', {}, {             get:    {method: 'GET'},             update: {method: 'POST'}         });     }); 

So it is supposed to be used like this:

        scope.user = User.get( {username: 'bob'}  );    // GET          console.log( JSON.stringify(scope.user) )       // {"$promise":{},"$resolved":false}  

So, when I send GET request, it goes OK, building this ur + params:

http://localhost:9000/rest/usersettings/bob 

Question, why I have: {"$promise":{},"$resolved":false}

If my GET request leads to json-response back from the server:{"username":"bob","email":"[email protected]"} then I'm expecting to have my scope.user filled by data.

Should I wait somehow promise is ready / resolved ?

like image 502
ses Avatar asked Nov 15 '13 18:11

ses


People also ask

What is $resource in AngularJS?

$resource documentation describes it as: A factory which creates a resource object that lets you interact with RESTful server-side data sources. $resource is most powerful when it's configured with a classic RESTful backend.

How to set http request header in AngularJS?

To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults. headers. get = { 'My-Header' : 'value' } .

What is$ http in AngularJS?

$http is an AngularJS service for reading data from remote servers.


2 Answers

User.get( {username: 'bob'} ) does not return your actual data immediately. It returns something will hold your data when the ajax returns. On that (the $promise), you can register an additional callback to log your data.

You can change your code to:

   scope.user = User.get( {username: 'bob'}  );    // GET    scope.user.$promise.then(function(data) {        console.log(data);    }); 
like image 133
Kos Prov Avatar answered Oct 03 '22 18:10

Kos Prov


You will get your data in there, but not immediately. Read the docs on ngResource:

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

like image 41
Stewie Avatar answered Oct 03 '22 19:10

Stewie