2

I'm using $resource for making restful request to the server. My code is

service.js

.factory('userServ',function($resource){
   return $resource('url/:id',{id:'@id'},{
          me: 'GET',isArray:false,url:'url2'}
});
})

I'm using this service in the controller like this

$scope.userDetails = userService.me();
console.log($scope.userDetails) // gives all the details of the user
console.log($scope.userDetails.username) // gives undefined. But username is there in the object

So how can I access that from the object

I'm nidhin
  • 2,592
  • 6
  • 36
  • 62

2 Answers2

0

In your aprroach, promise is not resolved. So you are not able to naccess data. Here,

  $scope.userDetails = userService.me(); 


Promise is not resolved. when you expand your Object you will see resolved:false. Although you will be able to see data inside $scope.userDetails you needed.

So, first you need to wait till promise is resolved.For this you can use .then method.

var CallApi = userService.me().$promise;  //Promise yet to be Resolved
       CallApi.then(function (res)){           //Promise resolved here
        $scope.userDetails = res;
        console.log($scope.userDetails)
        console.log($scope.userDetails.username)
      }
     })
Ved
  • 11,837
  • 5
  • 42
  • 60
  • 1
    Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". – abarisone Jul 19 '16 at 06:55
  • @abarisone I will follow your suggestion – Ved Jul 19 '16 at 09:35
0

Your resource object returns a promise. Read more about it here: https://docs.angularjs.org/api/ngResource/service/$resource

var myResource = $resource('url/:id',{id:'@id'},{
      me: 'GET',isArray:false,url:'url2'}
});

In order to get the data out of it you need to call the methods of the promise itself. They are GET, PUT and SAVE.

But here you only have a GET mentioned there.

So if you resolve your promise by calling

var myResult = [];
myResource.then(function(data){
    myresult = date;
});

Now, 'myResult' here will have your returned data.

It can also be called like this ():

.get({userId:123})
.$promise.then(function(user) {
  $scope.user = user;
});

Again I would recommend reading the angular docs to get a better understanding.

Alok
  • 1,290
  • 1
  • 11
  • 21