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
Related
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.
}
I'm trying to work out why the response of this service isn't saving to $scope.counter. I've added a function to my service fetchCustomers(p) which takes some parameters and returns a number, which I'd like to save to $scope.counter.
service
angular.module('app')
.factory('MyService', MyService)
function MyService($http) {
var url = 'URL'';
return {
fetchTotal: function(p) {
return $http.get(url, { params: p })
.then(function(response) {
return response.data.meta.total;
}, function(error) {
console.log("error occured");
})
}
}
}
controller
$scope.counter = MyService.fetchTotal(params).then(function(response) {
console.log(response);
return response;
});
For some reason though, this isn't working. It's console logging the value, but not saving it to $scope.counter. Any ideas?
If I understand your question correctly, you're setting $scope.counter to a promise, not the response.
MyService.fetchTotal(params).then(function(response) {
// Anything dealing with data from the server
// must be put inside this callback
$scope.counter = response;
console.log($scope.counter); // Data from server
});
// Don't do this
console.log($scope.counter); // Undefined
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
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 can't seem to get the $httpProvider.interceptors to actually intercept. I created a sample on JSFiddle that logs when the interceptor is run and when the $http response is successful. The request interceptor is run after the response is already returned as successful. This seems a bit backwards.
I can't use transformRequest because I need to alter the params in the config. That part isn't shown in the sample.
I'm using AngularJS 1.1.5
http://jsfiddle.net/skeemer/K7DCN/1/
Javascript
var myApp = angular.module('myApp', []);
myApp.factory('httpInterceptor', function ($q) {
return {
request: function (config) {
logIt('- Modify request');
return config || $q.when(config);
}
};
});
myApp.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
});
function MyCtrl($scope, $http) {
// Hit a server that allows cross domain XHR
$http.get('http://server.cors-api.appspot.com/server?id=8057313&enable=true&status=200&credentials=false')
.success(function (data) {
//logIt(data[0].request.url);
logIt('- GET Successful');
});
$scope.name = 'Superhero';
}
// Just the logging
var logs = document.getElementById('logs');
function logIt(msg) {
var e = document.createElement('div');
e.innerHTML = msg;
logs.insertBefore(e, logs.firstChild);
}
HTML
<div ng-controller="MyCtrl">Hello, {{name}}!</div>
<br/>
<div id="logs"></div>
If you want the option to accept/reject a request at interception time you should be using $httpProvider.responseInterceptors, see example below:
$httpProvider.responseInterceptors.push(function($q) {
return function(promise){
var deferred = $q.defer();
promise.then(
function(response){ deferred.reject("I suddenly decided I didn't like that response"); },
function(error){ deferred.reject(error); }
);
return deferred.promise;
};
});
EDIT Didn't read your comment, indeed responseInterceptors is now obsolete an that's how you do it instead:
$httpProvider.interceptors.push(function($q) {
return {
request: function(config){ return config; },
response: function(response) { return $q.reject(response); }
};
});
I learned something useful, thanks
The request interceptor isn't running after the data is returned. It's running before. Your logIt function inserts the newest message at the top. If you change your code to use the $log service, you'll see that the interceptor runs first.