Unable to access $http response data in Angular JS factory - angularjs

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
})
})

Related

write a unit test of this controller in angularjs which is calling a angularjs factory $http method

1.signup.js:
function register() {
UserService.signup($scope.user).then(function (resp){ //$scope.user contain a json object
if(resp.success){
}
});
}
2.UserService.js:
function signup(data) {
return $http.post('/api/appusers', data)
.then(function (res) {
},function(err) {
});
For testing $http you can use Angular $httpBackend https://docs.angularjs.org/api/ngMock/service/$httpBackend

angularjs how to catch http response data that sent by browser

As title, I want to catch Http response that sent by the browser.
Let say a redirect to "http://domain/api/something", actually, a GET request to "http://domain/api/something" which return a JSON data. How can I get that data on first load using AngularJs?
You should modify your code as below
app.service('feedbackService', function ($http) {
this.getFeedbackPaged = function () {
return $http.get('http://domain/api/something');
};
});
app.controller('feedbackController', function ($scope, feedbackService, $filter) {
// Constructor for this controller
init();
function init() {
feedbackService.getFeedbackPaged().then(function(data){
$scope.feedbackItems=data;
});
}
});
Use $http service as follows.
$http.get(
'http://domain/api/something'
).then(function successCallback(response) {
$scope.data = JSON.parse(response.data);
}, function errorCallback(response) {
// error handler
});
reference: https://docs.angularjs.org/api/ng/service/$http

Angular JS Service Error

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.
}

$q Promise in UI-Router Resolve?

Actually, this question can be simplified to "Return an $http or Restangular call result in a promise". My goal is to have a promise object that is resolved after an $http call completes:
var deferredCall= $q.defer();
Then this is resolved from the call:
$http.get (url)
.then(function(result){ deferredCall.resolve('Success' + result);},
function(){ deferredCall.resolve('Failure' + error););
Then I have a promise object that will be resolved when the call is complete (either succeeding or failing), this is what I want:
deferredCall.promise.then(function (value) {
return //something to pass to controller;
});
The goal is that the controller is instantiated whether the resolve succeds or fails. My problem? Resolve can only take a promise, so: `deferredCall.promise. How do I resolve this promise with the call above withing the Resolve / through a service? Are the results of a service method a promise?
Like if I make a service whose method makes the $http call and then returns deferredCall?
This is how we resolve data in our project:
Angular $routeProvider:
$routeProvider
.when('/something/something', {
templateUrl: 'somewhere/some-details.html',
controller : SomeController,
resolve : {
someItem : function (SomeService) {
return SomeService.getSomethingAll();
}
}
})
Controller:
var SomeController = function ($scope, someItem) {};
Data Service:
.service('SomeService', function (SomeUtils, $http) {
return {
getSomethingAll : function () {
return SomeUtils.promiseHttpResult($http.get("api/something/all"));
}
}
})
Utils Service:
.service("SomeUtils", function($q) {
return {
promiseHttpResult: function (httpPromise) {
var deferred = $q.defer();
httpPromise.success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject(arguments);
});
return deferred.promise;
}
}
})
Nice and simple. No skills required :) (DD)

Restangular with JSONP

I'm trying to use JSONP with Restangular. I'm using the Songkick API and when making a GET request I'm receiving no response data from a different domain but locally I receive data no problem.
I've created the following Factory for configuring Restangular and a controller. I'm a little unsure about how to use setDefaultRequestParams. Maybe the configuration is incorrect?
angular
.module('ModuleName')
.factory('RestFactory', Factory);
function Factory (Restangular) {
var factory = {
songkick: songkick
};
return factory;
function songkick () {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setJsonp = true;
RestangularConfigurer.setDefaultRequestParams('jsonp', {
callback: 'JSON_CALLBACK'
});
RestangularConfigurer.setDefaultRequestParams('get', {
reason: 'attendance',
apikey: 'xxxxxxxxxx'
});
RestangularConfigurer.setBaseUrl('http://api.songkick.com/api/3.0/');
RestangularConfigurer.setRequestSuffix('.json');
RestangularConfigurer.setDefaultHttpFields({cache: true});
});
}
}
angular
.module('ModuleName')
.controller('UserController', Controller);
function Controller ($stateParams, RestFactory) {
var user = this;
activate();
function activate () {
RestFactory.songkick().one('users/'+$stateParams.username+'/calendar')
.get()
.catch(function(response){
console.log("Error with status code", response.status);
});
}
}
Did you miss the JSONP option settings for Restangular?
Something like the following:
//JSonp
RestangularProvider.setJsonp(true);
RestangularProvider.setDefaultRequestParams('jsonp', {callback: 'JSON_CALLBACK'});
Documented here

Resources