Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting TypeError: Cannot read property 'query' of undefined

Tags:

angularjs

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?

like image 358
Arianule Avatar asked Apr 09 '16 16:04

Arianule


2 Answers

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.

like image 130
sheilak Avatar answered Nov 15 '22 04:11

sheilak


I had this issue a while ago and it took me hours to figure it out.

In certain cases you need to make sure that you inject "productResource" and "$scope" and follow a specific order. Let me demonstrate:

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

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

The above code will always work, but if you switch positions as seen below, in some cases (as I mentioned above), it won't work.

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

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

I never had this issue of making sure dependencies are injected in the correct order until today. If after all this your code is still not working then the issue is probably elsewhere.
I hope this helps.

like image 39
AllJs Avatar answered Nov 15 '22 04:11

AllJs