Error: $http is not defined - angularjs

I'm triying to make a controller/service for a state that get via my own query-method a list of clients.
It's weird because the "getAll" method works perfectly, the problem is query or some other get method... anyway, here is the service:
(function() {
'use strict';
angular
.module('omi.services')
.factory('cliente', clienteFactory);
clienteFactory.$inject = ['$http'];
function clienteFactory ($http) {
var baseUrl = 'http://localhost:3000/omi/v1/clientes/';
var service = {
create : create,
getAll : getAll,
getOne : getOne,
query : query,
remove : remove,
update : update
};
return service
function create (clienteData) {
// body...
} // end create
function getAll () {
return $http.get(baseUrl)
.success(getAllComplete)
.error(getAllOnError);
function getAllComplete (data) {
return data;
}
function getAllOnError (data) {
return data;
}
}
} // end facturaFactory
function getOne (cliente) {
return $http.get(baseUrl + cliente)
.success(getOneComplete)
.error(getOneOnError);
function getOneComplete (data) {
return data;
}
function getOneOnError (data) {
return data;
}
} // end getOne
function query (query) {
return $http.get(baseUrl + 'buscar' + query)
.success(queryComplete)
.error(queryOnError);
function queryComplete (data) {
return data;
}
function queryOnError (error) {
return data;
}
} // end query
function remove (factura) {
// body
} // end remove
function update (clienteData) {
// body...
} // end update
})();
it's not complete yet, but is the entire structure. So, the problem is fired in the controller:
(function(){
'use strict';
angular
.module('omi.controllers')
.controller('clientReportsResult', clientReports);
clientReports.$inject = ['$stateParams', 'cliente'];
function clientReports ($stateParams, cliente) {
/* jshint validthis: true */
var vm = this;
vm.clientes = [];
var id = $stateParams.data;
var query = "?id=" + id;
fire();
function fire () {
cliente.query(query).then(function(data) {
vm.clientes = data.data.clientes;
});
}
}
})();
It fire me this traceback:
"Error: $http is not defined
query#http://localhost:8080/js/services/clientes.service.js:55:7
fire#http://localhost:8080/js/controllers/clientes.reports.results.js:21:9
clientReports#http://localhost:8080/js/controllers/clientes.reports.results.js:18:7
invoke#http://localhost:8080/js/libs/angular/angular.js:4182:14
instantiate#http://localhost:8080/js/libs/angular/angular.js:4190:27
$ControllerProvider/this.$get</<#http://localhost:8080/js/libs/angular/angular.js:8449:18
$ViewDirectiveFill/<.compile/<#http://localhost:8080/js/libs/angular-ui-router/release/angular-ui-router.js:3897:28
invokeLinkFn#http://localhost:8080/js/libs/angular/angular.js:8213:9
nodeLinkFn#http://localhost:8080/js/libs/angular/angular.js:7722:1
compositeLinkFn#http://localhost:8080/js/libs/angular/angular.js:7075:13
publicLinkFn#http://localhost:8080/js/libs/angular/angular.js:6954:30
updateView#http://localhost:8080/js/libs/angular-ui-router/release/angular-ui-router.js:3839:23
$ViewDirective/directive.compile/<#http://localhost:8080/js/libs/angular-ui-router/release/angular-ui-router.js:3807:9
invokeLinkFn#http://localhost:8080/js/libs/angular/angular.js:8213:9
nodeLinkFn#http://localhost:8080/js/libs/angular/angular.js:7722:1
compositeLinkFn#http://localhost:8080/js/libs/angular/angular.js:7075:13
compositeLinkFn#http://localhost:8080/js/libs/angular/angular.js:7078:13
publicLinkFn#http://localhost:8080/js/libs/angular/angular.js:6954:30
$ViewDirectiveFill/<.compile/<#http://localhost:8080/js/libs/angular-ui-router/release/angular-ui-router.js:3905:9
invokeLinkFn#http://localhost:8080/js/libs/angular/angular.js:8213:9
nodeLinkFn#http://localhost:8080/js/libs/angular/angular.js:7722:1
compositeLinkFn#http://localhost:8080/js/libs/angular/angular.js:7075:13
publicLinkFn#http://localhost:8080/js/libs/angular/angular.js:6954:30
updateView#http://localhost:8080/js/libs/angular-ui-router/release/angular-ui-router.js:3839:23
$ViewDirective/directive.compile/</<#http://localhost:8080/js/libs/angular-ui-router/release/angular-ui-router.js:3801:11
$RootScopeProvider/this.$get</Scope.prototype.$broadcast#http://localhost:8080/js/libs/angular/angular.js:14702:15
transitionTo/$state.transition<#http://localhost:8080/js/libs/angular-ui-router/release/angular-ui-router.js:3218:11
processQueue#http://localhost:8080/js/libs/angular/angular.js:13170:27
scheduleProcessQueue/<#http://localhost:8080/js/libs/angular/angular.js:13186:27
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://localhost:8080/js/libs/angular/angular.js:14383:16
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://localhost:8080/js/libs/angular/angular.js:14199:15
$RootScopeProvider/this.$get</Scope.prototype.$apply#http://localhost:8080/js/libs/angular/angular.js:14488:13
done#http://localhost:8080/js/libs/angular/angular.js:9646:36
completeRequest#http://localhost:8080/js/libs/angular/angular.js:9836:7
requestLoaded#http://localhost:8080/js/libs/angular/angular.js:9777:1
" "<div ui-view="" class="details ng-scope">"
I'm triying to solve the problem, but i can't understand the problem, why this error appear's here? In the others controllers where i use the "getAll" method all is working fine!

The getOne function is outside of your clienteFactory factory function where $http is defined, and getAll is in the scope.
This is the structure you have:
function clienteFactory ($http) {
function getAll () {
}
}
function getOne () {
// $http is not defined here
}
Same is happening with query.
Put getOne and query inside the clienteFactory:
function clienteFactory ($http) {
function getAll () {
}
function getOne () {
}
function query() {
}
}

Related

How to handle $http errors when using factories in angular

I have a controller and factory like below and can easily handle success..But how can I handle errors?
Controller
app.controller("draftsCtrl", ["$scope", "DashboardFactory", function ($scope, DashboardFactory) {
DashboardFactory.drafts(function (successCallback) {
$scope.rooms listings= successCallback;
});
}]);
Factory
app.factory('DashboardFactory', function ($http) {
var DashboardFactory = {};
DashboardFactory.active_listings = function (successCallback) {
$http.get('active.json').success(successCallback);
}
DashboardFactory.inactive_listings = function (successCallback) {
$http.get('inactive.json').success(successCallback);
}
DashboardFactory.drafts = function (successCallback) {
$http.get('drafts.json').success(successCallback);
}
return DashboardFactory;
});
Instead of passing callbacks around, prefer proper promises workflow. For this make your service methods return promise objects:
app.factory('DashboardFactory', function ($http) {
var DashboardFactory = {};
DashboardFactory.active_listings = function () {
return $http.get('active.json');
}
DashboardFactory.inactive_listings = function () {
return $http.get('inactive.json');
}
DashboardFactory.drafts = function () {
return $http.get('drafts.json');
}
return DashboardFactory;
});
Then use promise API to handle success (then callback) and errors (catch):
app.controller("draftsCtrl", ["$scope", "DashboardFactory", function ($scope, DashboardFactory) {
DashboardFactory.drafts().then(function (response) {
$scope.rooms_listings = response.data;
})
.catch(function() {
console.log('Error ocurred');
});
}]);
"service" looks more elegantly in this case
function DashboardFactory($http) {
this.active_listings = function () {
return $http.get('active.json');
};
this.inactive_listings = function () {
return $http.get('inactive.json');
};
this.drafts = function () {
return $http.get('drafts.json');
};
});
DashboardFactory.$inject = ['$http'];
app.factory('DashboardFactory', DashboardFactory);

Angular variable in factory?

In a Angular app i have a couple of calls to a WebAPI service.
The first call, lets call it call1, should determine a true/false value of a variable.
So i have this
vm.call1.$promise.then(function (data) {
$rootScope.variable1 = data.variable;
});
This variable is to be used inside a factory i have;
myApp.factory('myStore', function ($http, $q, $rootScope) {
var showAll = $rootScope.variable1;
var get = function () {
if (showAll) {
//do this
} else {
//do this
}
};
return {
get: get
};
});
My problem is, that the factory above is loaded on pageload, and before the promise, and therefore the value is undefined.
How can i get the value, over to my factory, after the promise is complete?
No rootscope example: You can set the showAll flag manually:
vm.call1.$promise.then(function (data) {
myStore.setShowAll(data.variable);
});
and in the Factory:
myApp.factory('myStore', function ($http, $q) {
var showAll = 'true or false to be a default';
var get = function () {
if (showAll) {
//do this
} else {
//do this
}
};
var setShowAll = function(value) {
showAll = value;
};
return {
get: get,
setShowAll: setShowAll
};
});
Rootscope example: If you for some reason really need to use $rootScope for this you can just check for $rootScope value when you get, you don't have to store the value in a varibale.
myApp.factory('myStore', function ($http, $q, $rootScope) {
var get = function () {
if ($rootScope.variable1) {
//do this
} else {
//do this
}
};
return {
get: get
};
});

Not able to invoke the API Services when something is between Controller and Service in AngularJS?

I have Product.js file where
var productOPS = {
GetProduct: function () {
var promiseGet = getProducts();
}};
Now I want to invoke ProductService.js
app.service('crudService', function ($http) {
///product GET
this.getProducts = function () {
return $http.get("/api/ProductsAPI");
}
///end product
});
And ProductController.js is
app.controller('crudController', function ($scope, crudService) {
GetProducts();
//Function to load all Employee records
function GetProducts()
{
productOPS.GetProduct();
} } });
How can I invoke the Service from GetProduct of Products.js and pass the value back to ProductController
Error: getProducts() is not defined.
service should return object
app.service('crudService', function ($http) {
return {
getProducts: function () {
return $http.get("/api/ProductsAPI");
}
});
and then in controller you can sue it like this:
app.controller('crudController', function ($scope, crudService) {
crudService.getProducts().then( function(response){
$scope.products = response.data
});
});
$http returns promise that's why I used then but you can do success or whatever you want

Angular + Play Framework. When calling $http inside $scope.function server receives null

I'm facing the following problem with Play Framework and AngularJs. I'm trying to send an json object to my play controller but when I called the http request inside a scope function on my angular controller the server receives null. If I put the http call outside the scope function the server receives the json just fine. I appreciate any help guys
=== Scope Function ===
$scope.addComment = function () {
$scope.userComment = {};
$scope.userComment.client = $scope.client;
$scope.userComment.description = $scope.comment;
//Here is made the request to my server. If I put this piece of code out of
//this scope function works fine
ClientRepository.addComment($scope.userComment).then(function (response) {
$scope.comment = '';
$scope.client.contactsClientHistory.unshift(response);
$scope.tableComments.total = $scope.client.contactsClientHistory.length;
$scope.tableComments.reload();
});
}
=== On My Play Controller ===
public static Result addComment() {
try {
JsonNode request = request().body().asJson(); // Returns null
....More code here
=== Client Repository ===
'use strict';
define(['app', 'AbstractRepository'], function (app) {
app.factory('ClientRepository', ['Restangular', 'AbstractRepository', function (restangular, AbstractRepository) {
function ClientRepository() {
AbstractRepository.call(this, restangular, 'client');
this.addComment = function (newResource) {
return this.restangular.all(this.route + "/comment").post(newResource);
}
}
AbstractRepository.extend(ClientRepository);
return new ClientRepository();
}]);
});
=== AbstractRepository ===
'use strict';
define(['app', 'Alert'], function (app) {
app.factory('AbstractRepository', [ 'Alert', function (Alert) {
function AbstractRepository(restangular, route) {
this.restangular = restangular;
this.route = route;
restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
if (response.status == 400 || response.status == 500) {
Alert.handle(response);
} else if(response.status == 403){
Alert.error("commons.message.error.authFailure");
}
return true;
});
}
AbstractRepository.prototype = {
getList: function (params) {
return this.restangular.all(this.route).getList(params);
},
get: function (id) {
return this.restangular.one(this.route, id).get();
},
update: function (updatedResource) {
return updatedResource.put();
},
create: function (newResource) {
return this.restangular.all(this.route).post(newResource);
},
remove: function (id) {
return this.restangular.one(this.route, id).remove();
},
getPaginatedResult: function (params) {
return this.restangular.one(this.route).get(params);
}
};
AbstractRepository.extend = function (repository) {
repository.prototype = Object.create(AbstractRepository.prototype);
repository.prototype.constructor = repository;
};
return AbstractRepository;
}]);
});
It seam the problem was with the size of my json data. After I reduce the size of the json sent everything started working againg

How to get data by service and $cacheFactory by one method

I have a factory which get data from server. In the factory method I have used $cacheFactory to cache getting data. My code is as follows..
var buyersService = function ($http, $q,$cacheFactory) {
var serviceBase = '/api/OMData/';
var BuyersFactory = {};
buyersService.cache = $cacheFactory('cacheId');
BuyersFactory.GetBuyers = function () {
var dataList = buyersService.cache.get('BuyerData');
if (dataList != null && dataList.length > 0) {
return dataList;
}
else {
return $http.get(serviceBase + 'GetBuyers').then(
function (results) {
buyersService.cache.put("BuyerData", results.data);
return results.data;
});
}
}
app.factory('OMDataService', ['$http', '$q', '$cacheFactory', buyersService]);
});
Now I have called GetBuyers method from controller. My method is like below..
var BuyerController = function ($scope, BuyersService) {
$scope.Buyers = [];
init();
function init() {
getBuyers();
}
function getBuyers() {
BuyersService.GetBuyers()
.then(function (data) {
$scope.Buyers = data;
}, function (error) {
alert(error.message);
});
}
};
app.register.controller('BuyersController', ['$scope', 'OMDataService', BuyerController]);
When I have executed my controller method second time I have got an error message in promise part.
Object doesn't support property or method 'then'
The issue here is that your function returns two different things: either a promise or plain data. To remedy this, use another promise to control the flow and return that one as the result of the function.
Update your code to
var buyersService = function ($http, $q,$cacheFactory) {
var serviceBase = '/api/OMData/';
var BuyersFactory = {};
buyersService.cache = $cacheFactory('cacheId');
BuyersFactory.GetBuyers = function () {
var buyersDataIsAvailable = $q.defer();
var dataList = buyersService.cache.get('BuyerData');
if (dataList != null && dataList.length > 0) {
buyersDataIsAvailable.resolve(dataList);
}
else {
$http.get(serviceBase + 'GetBuyers').then(
function (results) {
buyersService.cache.put("BuyerData", results.data);
buyersDataIsAvailable.resolve(results.data);
});
}
return buyersDataIsAvailable.promise;
}
app.factory('OMDataService', ['$http', '$q', '$cacheFactory', buyersService]);
});

Resources