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

前端 未结 4 873
无人及你
无人及你 2020-12-04 15:48

Let\'s say a service like this:

   services.factory(\'User\', function($resource){
        return $resource(\'/rest/usersettings/:username\', {}, {
                 


        
相关标签:
4条回答
  • 2020-12-04 16:22

    This should work :

    User.get( {username: 'bob'} ).$promise.then(function(data) {
        scope.user = data.toJSON();
    });
    

    toJSON() cleans up Angular's internal properties ($$).

    0 讨论(0)
  • 2020-12-04 16:26

    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);
       });
    
    0 讨论(0)
  • 2020-12-04 16:29

    For now I use this (it seems I duplicate this question )

    User.get({
        username: 'bob'
    }, function(user) {
    
        user.$update(
            function(data, headers) {
                console.log("GOOD");
            },
            function(err, headers) {
                console.log("BAD");
            }
        );
    });
    
    0 讨论(0)
  • 2020-12-04 16:38

    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.

    0 讨论(0)
提交回复
热议问题