Get data from $ resource response in angular factory

I have this factory:

.factory("Member", function($resource) { var endpoint = "http://some valid url"; function generateMemberToken (id1, id2) { return $resource(endpoint, null, { query: { method: 'GET', headers: { 'id1': id1, 'id2': id2 } } }) } var member = { generateMemberToken : generateMemberToken } return member; }) 

and this controller:

  .controller('memberKeyCtrl', function($scope, Member){ $scope.generateMemberToken = function () { $scope.member = Member.generateMemberToken('123456789', '789456123').query(); console.log($scope.member); console.log($scope.member.someProperty); // problem here } 

$ scope.member is the JSON response from the API, i.e.

  {firstName:Joe, lastName:smith} 

I can see my console output for "$ scope.member", and it has an im property that is looking here, called .someProperty. I simply cannot extract this data, as I have it, see the line "// problem here" in the controller.

I assume that I somehow configured my factory incorrectly or did not make the property somehow accessible outside the factory. New to angular, so some problems understanding this.

Please let me know if more information is needed.

+4
source share
1 answer

The problem here is that the Async resource is $ resource and how the console interacts with your data.

.query() is an asynchronous call, which means that it does not return a value immediately; instead, it allows the code to continue flowing. The following statement applies to console.log($scope.member); , which does not immediately open $scope.member , to see its properties until they are used or verified. The next call is console.log($scope.member.someProperty); which $scope.member will expand to find someProperty . Since the callback of your .query() has not yet been returned, it will be log undefined . By the time you go to check what is in the first console.log , the callback is complete, and so the object looks like it has all the properties all the time, although in fact it is not, at the time they access attempts were made.

An easy way to handle this is to wrap the calls in .then() to make sure you don't execute them until the promise from .query() returns. To bind .then() , you need to access the returned promise, i.e.

 $scope.generateMemberToken = function () { $scope.member = Member.generateMemberToken('123456789', '789456123') .query().$promise.then(function(){ console.log($scope.member); console.log($scope.member.someProperty); // problem here }); }; 

The .query() syntax allows an anonymous callback, which allows you to pass a function that should be executed when query() , rather than a chain of .then() statements. For instance:

  $scope.generateMemberToken = function () { $scope.member = Member.generateMemberToken('123456789', '789456123') .query({}, function() { console.log($scope.member); console.log($scope.member.someProperty); // problem here }); } 
+6
source

All Articles