0

I'm using an Angular HTTP Resource to get some data from an API. The method on the API is actually a PUT, but returns an array of data. (Note, it's not my API)

It performs the HTTP Call perfectly and I can see in the Network on Google Developer Tools my response is right. However, I keep getting "TypeError: undefined is not a function" when trying to work with the response data.

Here are some of the different methods I've tried and each one gives the same TypeError:

HTTP Resource

.factory('Sports', ['$resource', 'SPORTS_CONFIG',
    function($resource, SPORTS_CONFIG) {
        return $resource(SPORTS_CONFIG.URL, {}, {
            get: {
                method: 'PUT', 
                isArray: true 
            }
        });
    }
])

Angular JS Attempts

// Construct Sports Body
var s = new Sports($scope.sport);

// Attempt 1
s.$get({}, function(data){

});

// Attempt 2
s.$get({}).then(function(data){

});

// Attempt 3
s.$get({}).$promise.then(data){

});

EDIT

After looking at my error code more, it looks like the error is occurring on 'isArray' in my HTTP Resource. When I set isArray to false, it errors because it expects an object but gets an array. When I keep it true, it errors and says TypeError: undefined is not a function. When I click the javascript line it's 'isArray'.

SECOND EDIT

I've gotten it to work using the following code:

$scope.teams = Sports.get($scope.sport);

However, $scope.teams = [0, $promise, $resolved] . How can I only get [0] instead of the $promise and $resolved?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jeremy Wagner
  • 485
  • 4
  • 9
  • 19

4 Answers4

0

the argument to your 'then' function should itself be a function.

eg:

s.$get({}).then(function (data){

});
Mike Atkins
  • 1,561
  • 13
  • 11
0

Your syntax looks wrong, follow this approach instead:

$http.get('/someurl').then(function(response) {
        //do something with response.data;
      }, function(errResponse) {
        console.error('Error while fetching data');
      });

As you can see you should be passing in a function which passes in the response from the server, and then you can get at your data.

mindparse
  • 6,115
  • 27
  • 90
  • 191
0

You can try something like this (with a function)

$http({
        method : "GET",
        url : "your_url"
    }).success(function(data, status, headers, config) {
        $scope.yourVariable= data;
    }).error(function(data, status, headers, config) {
        alert("Request failed. HTTP status:" + status);
    });
Iker Aguayo
  • 3,980
  • 4
  • 37
  • 49
0

Due to the edit above, this answer became outdated.

As I cannot comment right now, the way to get the just first item as you'd like is simple: $scope.teams = Sports.get($scope.sport)[0];

Marcos Sandrini
  • 400
  • 2
  • 10