0

I'm still learning Angular and am having some trouble accessing and using data across $resources. I have two api calls with two sets of data: wagers and users.

url:/users/me returns current username and id as an object

/wagers returns all wagers as an array. there is one field in wagers called userA, wagers?userA=(current user id) returns all the wagers whose userA=the current users id.

I am having trouble getting the (current user id) to dynamically pull in the current users id. My code is below:

//services
.factory('User', function($resource, $cookies){
    return $resource('users/me', {}, {
        query: {method:'GET', params:{}, isArray:false}
    })
})
.factory('Wager', function($resource, User){
    return $resource('wagers/', {}, {
        query: {method:'GET', params:{}, isArray:true}
    })
})

//controller
function WagerListCtrl($scope, $cookies, User, Wager){
    $scope.users = User.query
    $scope.wagers = Wager.query({"userA":user.id})
}
user2188552
  • 1
  • 1
  • 1
  • You might want to add parens on the query call like this: User.query() – Foo L Jun 26 '13 at 17:03
  • 1
    Another thing is $resource is only a promise, so $scope.users most likely won't be available until after the the controller is done executing. You should call Wager inside of a success callback. – Foo L Jun 26 '13 at 17:06
  • Can you clarify, how is "current user id" supposed to "dynamically pull in the current users id"? – Stewie Jun 26 '13 at 17:06

1 Answers1

3

First off, you need to call query with parentheses, like: User.query()

Secondly, $resource only provides promises, so $scope.users most likely won't be available until after the controller is done executing. You should call Wager inside of a success callback.

User.query({}, function(data) {
  $scope.user = data;
  // assuming user has an id field
  $scope.wagers = Wager.query({"userA":$scope.user.id});
});
Foo L
  • 10,977
  • 8
  • 40
  • 52