I am trying to call a function inside AngularJS service. Below is code-
EmployeeService.js:
/// <reference path="script.js" />
app.factory('fetchEmpService', function ($scope, $http) {
var fetchEmp= function()
{
var empList;
$http.get("EmpWebService.asmx/GetEmp")
.then(function (response) {
empList = response.data;
//return response.data;
//$scope.employees = response.data;
});
return empList;
}
return {
fetchEmp:fetchEmp,
};
});
My main script file where I am calling service is-
$scope.employees = fetchEmpService.fetchEmp();
It's not giving any error but no result is coming in it, seems it's returning blank. When I debugged by Browser Inspector I found that web service response is having data in Object form. So why it is not coming.
Another question is, can we not inject $scope in AngularJS service factory?
You cannot return emplist from outside the then function. The then function is asynchronous and emplist will not be populated until after the http call is complete.
You may want to do something more like this:
app.factory('fetchEmpService', function ($scope, $http) {
var service = this
service.fetchEmp: function() {
var empList;
return $http.get("EmpWebService.asmx/GetEmp")
.then(function (response) {
empList = response.data;
return empList;
});
}
return service
});
Then in your calling code do something like:
fetchEmpService.fetchEmp.then( function(emplList) {
// access the list here.
}
Related
I have this array I am getting through the following method:
var url= *url defined here*;
$scope.ViewProfile = function () {
$http.get(url)
.success(function (response) {
$scope.ProfileList = response;
$scope.FavNumbers = $scope.ProfileList[0].FavNumbers;
})
.error(function () {
});
}
I am required to edit the Fav Numbers list on the UI. and post it back to another url through http post url method. What I am stuck is with the concept of asynchronous calls, due to which I am unable to retrieve the favorite numbers list to be available for editing. Please help!
I have tried a method of using promises as follows:
app.factory('myService', function($http) {
var myService = {
async: function(url) {
var promise = $http.get(url).then(function (response) {
console.log(response);
return response.data;
});
// Return the promise to the controller
return promise;
}
};
return myService;
});
In my controller I am doing:
angular.module('JuryApp').controller('mycontroller', ['myService', function (myService) {
myService.async(url).then(function(d) {
$scope.data = d;
});
app.controller('MainCtrl', function( myService,$scope) {
// Call the async method and then do stuff with what is returned inside our own then function
myService.async().then(function(d) {
$scope.data = d;
});
});
But I keep getting the error 'd is not defined'. It keeps giving an error of some sort, where the debugger goes into an infinite loop or something.
You are overcomplicating it, I think. Async calls are actually pretty simple:
You're service:
app.factory("myService", ["$http", function($http) {
var MyService = {
getData: function(url) {
return $http.get(url); //$http returns a promise by default
}
};
return MyService;
})];
Your controller:
angular.module('JuryApp').controller('mycontroller', ['myService', function (myService) {
$scope.FavNumbers = [];
var url = "http://my.api.com/";
myService.getData(url).then(function(response) {
$scope.FavNumbers = response.data[0].FavNumbers;
});
}]);
That's all that you need to do.
i'm newby in angularjs i researched on the internet but i couldn't find any suitable solution for my problem. I made an http call to get some data from controller. The controller side is okay. But the client-side, promise does not waiting data. Here codes that I wrote ;
//service code
angular.module("myApp").service('$myService', function ($http, $q) {
this.getDataArray = function () {
var deferred = $q.defer();
$http.get('../Home/GetDataArray')
.success(function success(response) {
deferred.resolve(response);
})
.error(function () {
console.log("error getting data array");
deferred.reject();
});
return deferred.promise;
};
}
// controller-code
angular.module("myApp").controller('dataController', function ($scope, $http, $myService) {
$scope.getDataFromService = function () {
$myService.getDataArray().then(function (response) {
$scope.dataArray = response.data;
});
};
});
}
When i call the getDataFromService method at first $scope.dataArray is empty, but the second call, $scope.dataArray is filled with data. Where is the problem? Thanks for helps.
Not an angular expert myself. This is just how I did it when I ran into the same problem. Try this:
Controller:
angular.module("myApp").controller('dataController',[ '$scope', 'Service1', '$http', function ($scope, Service1, $http) {
var deferred = Service1.getDataArray().$promise;
return deferred.then(function successCallback(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$scope.dataArray = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
})
}])
and service:
var service = angular.module("myApp").service('myService', ['ngResource']);
myService.factory('Service1', ['$resource',
function ($resource) {
return $resource('../Home/GetDataArray', {}, {
get: { method: 'GET', isArray: true },
});
}])
The idea is that your service isn't the one that should wait for a return, your controller is. So you should wait for the promise in your controller not your service. In my example I am using factories because, well, that's how I got around it in my project, you can try and implement this directly if you don't want to use a factory.
I am trying to save $http response data in a variable inside angularJS factory. But I could not access the response outside the http method. It is showing undefined. I checked this link Injecting $scope into an angular service function() Please let me know how to handle this.
Below is the factory code:
angular.module('myapp')
.factory('CardNumberFactory',['$http', function ($http) {
// Service logic
var details={};
$http.get('scripts/services/mock.json')
.then(function(responce){
var resopnceData = responce.data;
details=resopnceData;
});
console.log(details);
return {details:details};
}]);
Because the $http service is asynchrony. You should do this like that:
angular.module('myapp')
.factory('CardNumberFactory',['$http', function ($http) {
var details={};
function getData() {
return $http.get('scripts/services/mock.json')
.then(function(response){
return {details: response.data}
});
}
return {
getData: getData
}
}]);
angular.module('myapp').controller('TestController, function($scope,CardNumberFactory) {
CardNumberFactory.getData().then(function(res) {
// res is the {details} object
})
})
I'm trying to call the getStuff function from my controller, but I get an error in the console saying that "undefined is not a function". I'm trying to return JSON from the GET and then store it in a $scope variable.
app.factory('UserInfo', function($http) {
var user = [];
return{
getStuff: function(){
user.push($http.get('api/users'));
return user;
},
testPost: function(){
return $http.post('api/users');
}
};
});
The factory is hooked up to the controller as follows
.controller('TwitterController', function($scope, $q, $interval, UserInfo) {
and here's the $scope function I'm using to call the factory function
$scope.datapls = function() {
UserInfo.getStuff().success(function(response){
console.log(response);
$scope.loaduser.push(response);
});
}
Thanks! I appreciate the help.
You're error refers to the .success() function - it doesn't exist.
It looks like you're trying to use promises. If that's the case, then you need to return the promise itself from your service.
Something like this (not tested, but an idea). You want to use the $q in your service, not your contorller.
The examples in the $q on AngularJS docs section are great.
So by doing this, your controller doesn't have to wait around for the data. As soon as it's resolved
app.service('UserInfo', function($http, $q) {
this.getStuff = function(){
var deferred = $q.defer();
$http.get('api/users').success(function(data, status) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
}
}
);
And in your controller you can do this:
UserInfo.getStuff().then(function(dataFromService){
// dataFromService is used in here..
$scope.loaduser.push(dataFromService);
}, function(error) {
// the error will come in via here
});
According to the docs, $http in itself returns a promise, you can change your factory function in order to achieve what you trying to do:
app.factory('UserInfo', function($http) {
return{
getStuff: function(){
return $http.get('api/users'));
},
testPost: function(){
return $http.post('api/users');
}
};
});
and in the controller:
$scope.datapls = function() {
UserInfo.getStuff().then(function(response){
console.log(response);
$scope.loaduser.push(response);
});
}
In my angular module I wrote a generic http handler for all my ajax requests.'
I was expecting that I could use the service across controllers, but my problem is the promise seems to be global.
Once ControllerOne uses the mapi_loader service, when I load AnotherController (by ng-click="go('/$route_to_load_another_controller')"), AnotherController is loaded a promise that has already returned from ControllerOne even though the URL they fetch are totally different.
So I guess my question is how do I write a service I could use across controllers? Do I really need to write a separate service for each controller where their only difference in code is the URL passed for $http.jsonp?
angular.module('myAppControllers',[])
.service('mapi_loader', ['$http', function($http) {
var promise;
var myService = {
fetch: function(url) {
if ( !promise ) {
promise = $http.jsonp(url)
.then(function (response) {
return response.data.nodes;
});
}
return promise;
}
};
return myService;
}])
.controller('ControllerOne', ['$scope', 'mapi_loader', function ($scope, mapi_loader) {
mapi_loader
.fetch("http://host.com/mapi_data_for_controller_one?callback=JSON_CALLBACK")
.then(function(data) {
$scope.useme = data;
});
}])
.controller('AnotherController', ['$scope', 'mapi_loader', function ($scope, mapi_loader) {
mapi_loader
.fetch("http://host.com/mapi_data_for_another_controller?callback=JSON_CALLBACK")
.then(function(data) {
$scope.useme = data;
});
}])
;
try something like this
angular.module('myAppControllers',[])
.service('mapi_loader', function($http) {
var alreadyLoading = {};
return {
fetch: function(url) {
if ( url in alreadyLoading ) {
return alreadyLoading[url];
}
return alreadyLoading[url] = $http.jsonp(url)
.then(function (response) {
delete alreadyLoading[url];
return response.data.nodes;
});
}
};
})
.controller('ControllerOne', function ($scope, mapi_loader) {
...
})
.controller('AnotherController', function ($scope, mapi_loader) {
...
});