Arianule Arianule - 1 month ago 11
AngularJS Question

Getting TypeError: Cannot read property 'query' of undefined

I am familiarizing myself with AngularJS and making calls to a Web API backend and I get the error of


angular.js:13424 TypeError: Cannot read property 'query' of undefined


I have a productListController

(function ()
{
"use strict";
angular.module("productManagement").controller("ProductListController", ["productResource", ProductListController]);
function ProductListController($scope, productResource) {

productResource.query(function (data) {
$scope.products = data
});
}
})();


and I created a service called productResource

(function () {
"use strict";

angular.module("common.services").factory("productResource", ["$resource", "appSettings", productResource])

function productResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/products/:id").query();
}
}());


The appSettings is a constant that specifies a path.

Why is
query
undefined?

Answer

Your controller is expecting the following dependencies to be injected:

$scope, productResource

and actually you are injecting only "productResource" instead of "$scope", "productResource"

Your controller should be initialised like this:

angular.module("productManagement").controller("ProductListController", ["$scope", "productResource", ProductListController]);

function ProductListController($scope, productResource) {
    // ...
}

The names of the dependencies passed in need to be in sync with the parameters in the controller function declaration - at the moment when you are injecting "productResource" it is going into the $scope parameter.

Comments