0

Below is part of code from angularjs service. It may not a specific question to angular though.

The $http.get('/api/test/1').then ( ... returns promise and I like to process the data returned by the call back. I am getting error when accessing filter method.

Test.filter(data.Root);


TypeError: Object #<Object> has no method 'filter'

But, I could access the data variable in the same scope (previous line) though.

var testApp = angular.module('testApp.services', []);
testApp.factory('Test', function ($http, $rootScope) {
    var Test = {};
    var data = [];

    Test.filter = function (d) {
        ret = data.filter(function (el) {
            return el.Pid == d.Id;
        });
        return ret;
    };
    Test.data = function () {
        return data[1];
    };

    Test.start = function () {
        Test.asyncData = $http.get('/api/test/1')
            .then(function (response) {
                data = response;
                return Test.filter(data.Root);
            }, function (response) {
                Test.error = 'Can\'t get data';
                data = 'Error: ' + response.data;
                return data;
            });
    };

    return Test;
});
bsr
  • 57,282
  • 86
  • 216
  • 316

1 Answers1

1

I think your error is coming from:

ret = data.filter(...

The data variable, which you set to the response, doesn't have a filter method.

It is probably either not of the type you think it is, or you meant to call the filter method on something else.

Samuel Edwin Ward
  • 6,526
  • 3
  • 34
  • 62
  • data is an array and supports filter, and I use chrome. see link http://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes – bsr Sep 22 '12 at 02:43
  • Thank you. It was indeed data.filter the exception occurs. I am not sure why though. will accept the answer, if no other explanation to this. – bsr Sep 22 '12 at 04:02
  • Before calling `Test.filter` you set `data` to the `response` passed to the `$http.get` callback. I believe this is a JSON object and not an array. – Samuel Edwin Ward Sep 22 '12 at 16:03