Getting TypeError: unable to read undefined property request

I get to know AngularJS and call the web API backend and I get an error

angular.js: 13424 TypeError: Unable to read property request 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(); } }()); 

AppSettings is a constant specifying a path.

Why is query undefined?

+5
source share
2 answers

Your controller expects the following dependencies:

 $scope, productResource 

and in fact you only enter "productResource" instead of "$scope", "productResource"

Your controller should be initialized as follows:

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

The names of the dependent dependencies must be synchronized with the parameters in the declaration of the controller function - the moment you inject "productResource" , it goes into the $scope parameter.

+7
source

I had this question a while ago, and it took me several hours to figure it out.

In some cases, you need to make sure that you enter "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 shown below, in some cases (as I mentioned above) this will not work.

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

I have never encountered this problem to make sure that the dependencies are entered in the correct order until today. If after this your code still does not work, the problem is probably elsewhere.
Hope this helps.

+1
source

Source: https://habr.com/ru/post/1246783/


All Articles