Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
   });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...