jazzgot jazzgot - 2 months ago 7
AngularJS Question

Factory "is not defined" in AngularJS

I'm a beginner in Angular world, and I can't work out why I'm still getting "not defined" error. Here is my code:

angular.module('dopasujApp').factory('getProducts', ['$http', function ($http) {
var dataFactory = {};
dataFactory.sort='ASC';
dataFactory.orderBy='PRODUCT_NAME';
dataFactory.search='a';
dataFactory.filters={};
dataFactory.filters.ATTRIBS=[46,25];
dataFactory.filters.SIZE=[165,40];

getProducts.listProducts = function() {
var request = $http({
method: "POST",
url: "http://******/backend/internalAPI.php?action=getListing&fit=1&limit=10&vendor=20",
headers: {
'Content-Type': 'application/json'
},
data: {
data: dataFactory
}
});

var products = angular.fromJson(request);

return products;
}

return false;

}]);


And here goes my controller (just for testing purposes now).

angular.module('dopasujApp')
.controller('MainCtrl', ['getProducts', '$scope','$rootScope',
function (getProducts, $scope,$rootScope) {
console.log(getProducts.listProducts())
}
]);

Answer
  1. getProducts variable in factory is not defined. The name you used before is just informative name for angular

  2. In your factory you are returning "false" as actual result. So angular treats your "false" as result.

It should look like that :

angular.module('dopasujApp').factory('getProducts', ['$http', function ($http) {
    var dataFactory = {}, getProducts = {};
    dataFactory.sort='ASC';
    dataFactory.orderBy='PRODUCT_NAME';
    dataFactory.search='a';
    dataFactory.filters={};
    dataFactory.filters.ATTRIBS=[46,25];
    dataFactory.filters.SIZE=[165,40];

    getProducts.listProducts = function() {
        return $http({
            method: "POST", 
            url: "http://******/backend/internalAPI.php?action=getListing&fit=1&limit=10&vendor=20",
            headers: {
                'Content-Type': 'application/json'
            },
            data: {
                data: dataFactory
            }
        });
    }

    return getProducts;

}]);

Controller

angular.module('dopasujApp').controller('MainCtrl', ['getProducts', '$scope','$rootScope', 
    function (getProducts, $scope,$rootScope) {
        getProducts.listProducts().then(function(res) {
            console.log(res.data);
        });
    }
]);

EDIT:

Also note, that $http returns promise, but not actual query result, updated my example accordingly

Comments