using factory in angularjs getting Error: [$injector:undef] - angularjs

I am creating a new angular App and using factory but when i am am getting an error which is
Error: [$injector:undef] http://errors.angularjs.org/1.4.5/$injector/undef?p0=Data
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:6:416
at Object.$get (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:37:32)
at Object.e [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:39:96)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:40:410
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:38:308)
at e (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:39:64)
at Object.g.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:39:213)
at b.$get (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:80:257)
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js:12:165)
var app = angular.module('testapp', ['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/userlist', {
title: 'List of all the users',
templateUrl: 'userlist.html',
controller: 'listuser'
})
.when('/profile',{
title:'user detail page',
templateUrl:'profile.html',
controller:'listuser'
})
.otherwise({
redirectTo: '/userlist'
});
}])
app.factory("Data", ['$http','$log',
function ($http,$log) {
var obj = {};
obj.post = function (q, object) {
return $http({
method: 'POST',
url:'userdetail.php',
data: object.user
})
.then(function (results) {
$log.log(results);
return results.data;
});
};
}]);
app.controller('listuser',['Data', function ($scope,$http,$log,$window,Data) {
$scope.userdetail = {};
var init = function () {
$http({
method: 'POST',
url: 'apisource.php',
})
.then(function (results) {
$scope.data=results.data;
});
};
init();
$scope.douserdetail = function(user) {
Data.post({
user: user
}).then(function (results) {
if (results.status == "success") {
//$location.path('dashboard');
}
});
};
}]);

Factory functions in angular are expected to return an object, but your "Data" factory does not return anything. Simply add the following at the end of your factory function to fix the issue:
return obj;

Have a look at the link provided in your stacktrace. Your factory has to return a value:
app.factory("Data", ['$http','$log',
function ($http,$log) {
var obj = {};
...
return obj;
}]);

There are many error, in controller your are using $http, what is the purpose
You are calling init() inside the init which will cause the infinite loop
You service is not returning anything
I will suggest to check the basics angular first

Related

cannot access function from factory through directive in AngularJs

/TypeError: Cannot read property 'getToken' of undefined/
I am trying to call getToken function which is defined in the factory function.
Both directive and factories are in separate .js file
but it is throwing an error and is not able to access the function.
angular.module('pesaveWeb')
.directive('goals', function goalsDrctv ($timeout) {
'use strict';
return {
restrict: 'E',
replace: true,
scope: true,
templateUrl: "js/directives/goals.tmpl.html",
controllerAs: 'savings',
controller: function ($routeParams, $scope,
savingsFactory,tokenFactory) {
this.message = {};
var token=tokenFactory.getToken();
var getGoals = savingsFactory.getGoals(token);
if (getGoals) {
getGoals.then( angular.bind(this, function (response) {
savingsFactory.message = response;
this.message = savingsFactory.message;
alert(JSON.stringify(this.message));
}) );
}
}
}
});
angular.module('pesaveWeb').factory('tokenFactory', function tokenFactory ($http,$routeParams) {
'use strict';
var obj = {};
obj.getToken = function () {
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function (data) {
})
.error(function (data) {
});
};
});
Your factory function needs to return the obj you are using to bind the function to.
angular.module('pesaveWeb').factory('tokenFactory', function tokenFactory ($http,$routeParams) {
'use strict';
var obj = {};
obj.getToken = function () {
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function (data) {
})
.error(function (data) {
});
};
return obj;
});
Also, another potential problem is the getToken() function might not work as expected. You should use a "promise" for resolving the value of token in your getToken() function using Angular's $q service. Check out its documentation here

Cannot set property from angularjs service

I am trying to set value in html page from angularjs controller.
I am getting value from web api in service but I have issue that I am always getting error:
TypeError: Cannot set property 'messageFromServer' of undefined
But I can't figure what am I doing wrong here. What am I missing?
On the html part I have:
<div ng-app="myApp" ng-controller="AngularController">
<p>{{messageFromServer}}</p>
</div>
In the controller I have:
var app = angular.module('myApp', []);
app.controller('AngularController', ['$scope', 'messageService', function ($scope, messageService) {
$scope.messageFromServer = "When I set it here it works!"
messageService.getMessage();
}]);
app.service('messageService', ['$http', function ($http) {
this.getMessage = function ($scope) {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
$scope.messageFromServer = data;
console.log(data);
}).error(function (data) {
console.log(data);
})
};
}]);
Basically the problem is, you missed to $scope object to the service getMessage method. But this is not a good approach to go with. As service is singleton object, it shouldn't manipulate scope directly by passing $scope to it. Rather than make it as generic as possible and do return data from there.
Instead return promise/data from a service and then assign data to the scope from the controller .then function.
app.service('messageService', ['$http', function ($http) {
this.getMessage = function () {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
//you could have do some data validation here
//on the basis of that data could be returned to the consumer method
//consumer method will have access only to the data of the request
//other information about request is hidden to consumer method like headers, status, etc.
console.log(response.data);
return response.data;
}, function (error) {
return error;
})
};
}]);
Controller
app.controller('AngularController', ['$scope', 'messageService',
function ($scope, messageService) {
$scope.messageFromServer = "When I set it here it works!"
messageService.getMessage().then(function(data){
$scope.messageFromServer = data;
});
}
]);
Don't use $scope in your service, just return the promise from $http.
var app = angular.module('myApp', []);
app.service('messageService', ['$http', function ($http) {
this.getMessage = function () {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
});
};
}]);
app.controller('AngularController', ['$scope', 'messageService', function ($scope, messageService) {
messageService.getMessage().then(function(data) {
$scope.messageFromServer = data;
});
}]);
In this example you can unwrap the promise in your controller, or even better you can use the router to resolve the promise and have it injected into your controller.
app.config(function($routeProvider) {
$routeProvider.when('/',{
controller: 'AngularController',
templateUrl: 'views/view.html',
resolve: {
message: function(messageService) {
return messageService.getMessage();
}
}
});
});
Then in your AngularController, you'll have an unwrapped promise:
app.controller('AngularController', ['$scope', 'message', function ($scope, message) {
$scope.messageFromServer = message;
}]);

"$injector:unpr Unknown provider" after adding resolve in $stateProvider

I searched already for similar problems but couldn't figure out what the problem is in my specific case. Maybe one of you has an idea?
My code was executing with out an error but I had to add resolve to my $stateProvider. After doing so I got following error:
Error: [$injector:unpr] Unknown provider: rquoteShipmentListProvider <- rquoteShipmentList <- vendorQuoteCtrl http://errors.angularjs.org/1.4.7/$injector/unpr?p0=rquoteShipmentListProvider%20%3C-%20rquoteShipmentList%20%3C-%20vendorQuoteCtrl at Anonymous function (https://code.angularjs.org/1.4.7/angular.js:4289:13) ...
My code:
var app = angular.module("offerModul", ["ui.router", "ui.bootstrap"]);
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state("main",{
url: "/",
controller:'vendorQuoteCtrl',
templateUrl:'src/html/vendorQuoteRequest.html',
resolve: {
rquoteShipmentList: function(shipmentService) {
return shipmentService.loadquoteShipments();
}
}
});
});
app.controller('vendorQuoteCtrl', ['$scope', 'shipmentService', 'carrierService', 'chargesService', 'rquoteShipmentList', function($scope, shipmentService, carrierService, chargesService, rquoteShipmentList) {
$scope.quoteShipmentList = rquoteShipmentList;
$scope.open = function ()
{
init();
}
function init() {
$scope.quoteShipmentList = shipmentService.getquoteShipments();
}
}]);
app.service('shipmentService', ['$http', function ($http) {
var quoteShipmentList = null;
return {
loadquoteShipments: function () {
$http.get("./src/data/getShipments.php",{
cache: true})
.success(function (response) { quoteShipmentList = response; alert("quoteShipmentList:" + quoteShipmentList);})
.error(function (data, status) {
alert("error getting Quotes! status:"+status);
});
alert("should be set:" + quoteShipmentList);
return quoteShipmentList;
},
getquoteShipments: function () {
return quoteShipmentList;
}
};
}]);
Before adding resolve my code is executed without an error. The code before:
var app = angular.module("offerModul", ["ui.router", "ui.bootstrap"]);
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state("main",{
url: "/",
controller:'vendorQuoteCtrl',
templateUrl:'src/html/vendorQuoteRequest.html'
});
});
app.controller('vendorQuoteCtrl', ['$scope', 'shipmentService', 'carrierService', 'chargesService', function($scope, shipmentService, carrierService, chargesService) {
$scope.quoteShipmentList = shipmentService.loadquoteShipments();
$scope.open = function ()
{
init();
}
function init() {
$scope.quoteShipmentList = shipmentService.getquoteShipments();
}
}]);
app.service('shipmentService', ['$http', function ($http) {
var quoteShipmentList = null;
var shipmentList = null;
return {
loadquoteShipments: function () {
$http.get("./src/data/getShipments.php",{
cache: true})
.success(function (response) { quoteShipmentList = response; alert("quoteShipmentList:" + quoteShipmentList);})
.error(function (data, status) {
alert("error getting Quotes! status:"+status);
});
alert("should be set:" + quoteShipmentList);
return quoteShipmentList;
},
getquoteShipments: function () {
return quoteShipmentList;
}
};
}]);
Thank you very much for your help!!!
Like recommended in other posts I deleted ng-controller from my html BUT I didn't saw that there was another one in a modal-dialog (?:-/).
Removing that tag removed the error!
Thank you for trying to help!
there is a problem in the resolve. you have to inject your service shipmentService in the resolve like we inject in controller.
Something like :
resolve: {
rquoteShipmentList: ['rquoteShipmentList', function (rquoteShipmentList){
return shipmentService.loadquoteShipments();
}],
}

AngularJS ui-router resolve is undefined

I have moved from using ngRoute to ui-router. I am trying to resolve a Factory call in the route for use in the controller but it is undefined when output to the console. Here is the Factory:
'use strict';
angular.module('angular10App')
.factory('AirportService', function ($http) {
return {
getAirports: function () {
var airports = $http.get('../json/airports.json')
.then(function (response) {
console.log(response.data); //Outputs an array of objects
return response.data;
});
}
});
Here is the Route:
'use strict';
angular.module('angular10App')
.config(function ($stateProvider) {
$stateProvider
.state('selectFlights', {
url: '/select_flights',
templateUrl: 'app/selectFlights/selectFlights.html',
controller: 'SelectFlightsCtrl',
resolve: {
AirportService: 'AirportService',
airports: function (AirportService) {
return AirportService.getAirports();
}
},
});
});
and here is the controller:
'use strict';
angular.module('angular10App')
.controller('SelectFlightsCtrl', function ($scope, airports) {
$scope.selectedAirport = null;
$scope.airports = airports;
console.log($scope.airports); //undefined
});
Try changing your resolve block to this:
resolve: {
airports: function (AirportService) {
return AirportService.getAirports();
}
}
And modify the getAirPorts function into:
function getAirports () {
// You need to return the $http promise (or in your case, 'var airports');
return $http.get('../json/airports.json')
.then(function (response) {
console.log(response.data); //Outputs an array of objects
return response.data;
});
}

Angular Factor Call not working

I am trying to call the update / put method in the factory which will in turn save the changes on the form to the database via an API call. But I get a console error below. The update function is getting called from the button click fine, but it doesn't call the factory and API from there. What am I missing? Thank you!
I updated my code with the suggestion below but now have this error:
My console error: "Error: [$injector:unpr] http://errors.angularjs.org/1.2.10/$injector/unpr?p0=%24resourceProvider%20%3C-%20%24resource%20%3C-%20memberUpdate
var securityApp = angular.module('securityApp', ['ngRoute']).
config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'PartialPages/members.html',
controller: 'membersController'
})
.when('/memberDetail/:memberID', {
templateUrl: 'PartialPages/memberDetail.html',
controller: 'memberDetailController'
})
.when('/memberEdit', {
templateUrl: 'PartialPages/memberEdit.html',
controller: 'memberEditController'
});
});
securityApp.factory('memberUpdate', function ($resource) {
return $resource('/api/Members/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
securityApp.controller('memberDetailController', function ($scope, $http, $routeParams, memberUpdate) {
var id = $routeParams.memberID;
$http.get('/api/Members/' + $routeParams.memberID).success(function (data) {
$scope.member = data;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
})
$scope.update = function () {
memberUpdate.update({ id: id }, $scope.member);
};
});
You need to inject memberUpdate into the controller dependencies.
securityApp.controller('memberDetailController', function ($scope, $http, $routeParams, memberUpdate) {
var id = $routeParams.memberID;
$http.get('/api/Members/' + $routeParams.memberID).success(function (data) {
$scope.member = data;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
})
$scope.update = function () { // you don't need to pass $scope and memberUpdate since they are already available into the scope
memberUpdate.update({ id: id }, $scope.member);
};
});
$resource is in a different module so you need to include it.
var securityApp = angular.module('securityApp', ['ngRoute', 'ngResource']).
her how you install it https://docs.angularjs.org/api/ngResource

Resources