AngularJS - Factory - TypeError: Cannot read getSpec property from undefined

I am starting with AngularJS and I am having some problems trying to use a factory from a controller.

I have the following factory

angular.module('testingApp') .factory('factoryService', function ($http) { // Service logic var getSpec = function(p) { return $http.get('http://someurl//?p=' + p); }; return { getSpec: getSpec }; }); 

and then I will try to use it from the controller as follows

 angular.module('testingApp') .controller('ServiceincientsCtrl',[ function (factoryService,$scope) { console.log('Starting Service Incident Controller'); factoryService.getSpec('AAA').then(function(response){ $scope.result = response.data; }, function(error){ console.log('opsssss' + error); }); }]); 

But when I try to run it, I get the following message

 TypeError: Cannot read property 'getSpec' of undefined 

I don’t know what I don’t have, it should be a newbbie error, I googled, and I tried many examples with the same result.

Any ideas on what I'm doing wrong?

Thanks!

+5
source share
2 answers

It looks like you are misusing the notation of an array of dependencies. Please see the code below. Please add ' factoryService ' and ' $scope ' as elements of the array.

 .controller('ServiceincientsCtrl', ['factoryService', '$scope', function(factoryService, $scope) { console.log('Starting Service Incident Controller'); factoryService.getSpec('AAA').then(function(response) { $scope.result = response.data; }, function(error) { console.log('opsssss' + error); }); }]); 

Angular documentaion on dependency injection .

+11
source

First of all, you did not specify your controller correctly. It should look like this:

 .controller('ServiceincientsCtrl',['$scope', 'factoryService', function($scope, factoryService) { 

I personally use Service , as I consider them more readable.

Here your factory will look like Service :

 myApp.service('factoryService', function ($http) { this.getSpec = function(p) { return $http.get('http://someurl//?p=' + p); } }); 

This will work with your current controller.

+3
source

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


All Articles