Using $http inside my own service - variable does not persist - angularjs

I try to use a service to get some data from server, but I had a problem: even the console log out the length when I print 'myData.length', when I try to find length of '$scope.test' controller variable it tell me that it is undefined.
What I should to do to use a $http service inside my own service?
app.controller('mainCtrl', ['$scope', 'mapServ',
function($scope, mapServ) {
$scope.test = [];
$scope.test = mapServ.test;
console.log('$scope.test = ' + $scope.test.length);
}]);
app.factory('mapServ', ['$http', function ($http) {
var path = "file path to my server data";
var out = {};
var myData = [];
out.test = $http.get(path).then(function (response) {
myData = response.data;
console.log(myData.length);
});
return out;
}]);

Take these service and controller as an example and you should follow John Papa's style guide while writing the code.
Service
(function() {
'use strict';
angular
.module('appName')
.factory('appAjaxSvc', appAjaxSvc);
appAjaxSvc.$inject = ['$http', '$q'];
/* #ngInject */
function appAjaxSvc($http, $q) {
return {
getData:function (path){
//Create a promise using promise library
var deferred = $q.defer();
$http({
method: 'GET',
url: "file path to my server data"
}).
success(function(data, status, headers,config){
deferred.resolve(data);
}).
error(function(data, status, headers,config){
deferred.reject(status);
});
return deferred.promise;
},
};
}
})();
Controller
(function() {
angular
.module('appName')
.controller('appCtrl', appCtrl);
appCtrl.$inject = ['$scope', '$stateParams', 'appAjaxSvc'];
/* #ngInject */
function appCtrl($scope, $stateParams, appAjaxSvc) {
var vm = this;
vm.title = 'appCtrl';
activate();
////////////////
function activate() {
appAjaxSvc.getData().then(function(response) {
//do something
}, function(error) {
alert(error)
});
}
}
})();

In your code you do not wait that $http has finished.
$http is an asynchronous call
You should do it like this
app.controller('mainCtrl', ['$scope', 'mapServ',
function($scope, mapServ) {
$scope.test = [];
$scope.test = mapServ.test.then(function(response) {
console.log(response.data);
}, function(error) {
//handle error
});;
}
]);
app.factory('mapServ', ['$http', function($http) {
var path = "file path to my server data";
var out = {};
var myData = [];
out.test = $http.get(path);
return out;
}]);

$http call that you are making from factory is asynchronous so it will not wait , until response come, it will move on to the next execution of the script, that is the problem only try Weedoze's asnwer, it is correct way to do this.

Related

Angular service passing data to controller

I am trying to create a service that passes data to controller.
I cannot see any errors in the console but yet the data won't show. What exactly am I doing wrong?
Service
app.service('UsersService', function($http, $q) {
var url = '/users';
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
parsePromise.resolve(data);
});
return parsePromise.promise;
});
Controller
app.controller('contactsCtrl',
function($scope, $routeParams, UsersService) {
// Get all contacts
UsersService.get().then(function(data) {
$scope.contacts = data;
});
});
success is now deprecated.
app.service('UsersService', function($http) {
var url = '/users';
this.get = function() {
return $http.get(url).then(function(response) {
return response.data;
});
}
});
you are referring to UsersService.get(), so you must define the .get() function to call:
app.service('UsersService', function($http, $q) {
var url = '/users';
this.get = function() {
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
parsePromise.resolve(data);
});
return parsePromise.promise;
}
});

Angularjs Reference Error: service is not defined

I would like to inject my service file into my controller using AngularJS so I can make the $http calls, but when I do so, I receive an error that it isn't defined.
Here's my service call in a separate file that has been included into the index.html.
(function () {
'use strict';
angular.module('App')
.service('MemberService', ['$http', '$q',
function MemberService($http, $q) {
var svc = this;
svc.postMembers = _postMembers;
var deferred = $q.defer();
_postMembers.$http({
method: 'POST',
url: '/api/MemberSearch',
data: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (result) {
deferred.resolve(result)
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
console.log("promise", deferred.promise);
}]);
})();
Now, here's the controller.js
(function () {
'use strict';
angular
.module('App')
.controller('MemberController', MemberController);
MemberController.$inject = ['$scope', '$http', '$q', 'MemberService', MemberService];
function MemberController($http, MemberService) {
var vm = this;
vm.search = {}; //a blank object to contain form data
vm.memberSearchForm = null; //reference to the actual form in html
vm.memberResult = []; //a blank object to handle returned data
vm.memberSearch = _memberSearch;
vm.showErrors = false;
function _memberSearch() {
vm.showErrors = true;
console.log("inside _memberSearch");
var promisePost = MemberService.postMembers(vm.search)
console.log("vm.search", vm.search);
}
};
})();
Any help is much appreciated.

Ionic Framework: called service

I using this to save data to the service and called it again in the same controller after save it. But it didn't have value for the service. When i call the service again in another controller, it gave me the result i want.
.controller('HomeCtrl', function ($scope) {
$http.get(URL).success(function(data){
Service.thisData(data);
Service.getData(); // value = 1000
});
// call save data from service
// i didn't get any data from the service
Service.getData(); // value = undefined
};
So how do i get the data from service except inside the http.get??
Thanks.
I suggest you to write the api calls in a factory, and call that service in the controller, in which you need the data. You can call the same service in multiple controllers also.
As per my understanding, i hope this is your requirement. If not, please let me know, i will try my best.
You can refer to the plunkr code
http://plnkr.co/edit/G9MkVMSQ4VjMw8g2svkT?p=preview
angular.module('mainModule', [])
.factory('apiCallService', ['$http', '$q', '$log',
function ($http, $q, $log) {
var instance = {};
var config = null;
instance.apiCallToServer = function (config) {
var deferred = $q.defer();
$http(config)
.success(function (data, status, header, config) {
deferred.resolve(data);
})
.error(function (data, status, header, config) {
deferred.reject(status);
});
return deferred.promise;
};
return instance;
}])
.controller('FirstCtrl', ["$scope", "$log", "$location", "apiCallService",
function ($scope, $log, $location, apiCallService) {
var config = {
method: "get",
url: "/path"
};
$scope.successCallback = function (data) {
$log.log("success.");
$scope.data = data;
//data will be stored in '$scope.data'.
};
$scope.failureCallback = function (status) {
$log.log("Error");
};
apiCallService
.apiCallToServer(config)
.then($scope.successCallback, $scope.failureCallback);
}]);

AngularJS : Factory Service Controller $http.get

I am trying to retrieve the "cart" in the following way Factory->Service->Controller.
I am making an $http call but it is returning an object. If I debug I can see that the request is made and is retrieving the data (in the network section of the debugger).
angular.module('companyServices', [])
.factory('CompanyFactory', ['$http', function($http){
return {
getCart: function(cartId) {
var promise = $http.get('company/Compare.json', {params: {'wsid': cartId}})
success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
return "error: " + status;
});
}
};
}]);
angular.module('itemsServices', [])
.service('ItemsServices', ['CompanyFactory', function(CompanyFactory){
var cartId = new Object();
this.getCartId = function(){
return cartId;
};
this.cartId = function(value){
cartId = value;
};
this.getCart = function(){
return CompanyFactory.getCart(this.getCartId()).then(function(data){return data});
};
};
.controller('CompareItemsCtrl', ['$scope', '$location', 'ItemsServices', function($scope, $location, ItemsServices){
var params = $location.search().wsid;
ItemsServices.cartId(params);
console.log('ItemsServices.getCart()');
console.log(ItemsServices.getCart());
};
Thank you
Since $http returns a promise, I think you would be better of passing in your success and error functions to getCart()
.controller('CompareItemsCtrl', ['$scope', '$location', 'ItemsServices', function($scope, $location, ItemsServices){
var params = $location.search().wsid;
ItemsServices.cartId(params);
console.log('ItemsServices.getCart()');
console.log(ItemsServices.getCart());
ItemsService.getCart().then(function(response){
console.log('success');
},function(response){
console.log('error');
});
};

Return factory data to controller always undefined

Trying to return data from the factory and logging within the factory outputs the correct data, but once passed to the controller it is always undefined. If I have my factory logic inside the controller it will work fine. So it must be something simple Im missing here?
Application
var app = angular.module('app', []);
app.controller('animalController', ['$log', '$scope', 'animalResource', function($log, $scope, animalResource) {
$scope.list = function() {
$scope.list = 'List Animals';
$scope.animals = animalResource.get(); // returns undefined data
$log.info($scope.animals);
};
$scope.show = function() {};
$scope.create = function() {};
$scope.update = function() {};
$scope.destroy = function() {};
}]);
app.factory('animalResource', ['$http', '$log', function($http, $log) {
return {
get: function() {
$http({method: 'GET', url: '/clusters/xhrGetAnimals'}).
success(function(data, status, headers, config) {
//$log.info(data, status, headers, config); // return correct data
return data;
}).
error(function(data, status, headers, config) {
$log.info(data, status, headers, config);
});
},
post: function() {},
put: function() {},
delete: function() {}
};
}]);
Log Info
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
200 function (name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
} Object {method: "GET", url: "/clusters/xhrGetAnimals"}
Your get() method in service is not returning anything. The return inside the success callback only returns from that particular function.
return the $http object
Che this example that is how you use the promises and you return the factory then you access the methods injecting the service on your controller
Use dot syntax to access the function you define on the service
'use strict';
var app;
app = angular.module('app.formCreator.services', []);
app.factory('formCreatorService', [
'$http', '$q', function($http, $q) {
var apiCall, bjectArrarContainer, deferred, factory, webBaseUrl, _getFormElementsData;
factory = {};
deferred = $q.defer();
bjectArrarContainer = [];
webBaseUrl = 'https://tools.XXXX_url_XXXXX.com/XXXXXXX/';
apiCall = 'api/XXXXX_url_XXXX/1000';
_getFormElementsData = function() {
$http.get(webBaseUrl + apiCall).success(function(formElements) {
deferred.resolve(formElements);
}).error(function(err) {
deferred.reject(error);
});
return deferred.promise;
};
factory.getFormElementsData = _getFormElementsData;
return factory;
}
]);
then do it like this for example
'use strict';
var app;
app = angular.module('app.formCreator.ctrls', []);
app.controller('formCreatorController', [
'formCreatorService', '$scope', function(formCreatorService, $scope) {
$scope.formElementsData = {};
formCreatorService.getFormElementsData().then(function(response) {
return $scope.formElementsData = response;
});
}
]);

Resources