$http POST response from service to controller - angularjs

How to get the response from Service in below case??
Service:
app.factory('ajaxService', function($http) {
updateTodoDetail: function(postDetail){
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
})
.success(function(response){
//return response;
});
}
})
Controller:
updated_details = 'xyz';
ajaxService.updateTodoDetail(updated_details);
In th above case, i POST the data through Controller and it was working fine but now i want the response to come in my Controller.
How to achive that??

$http returns a promise:
Return the promise
updateTodoDetail: function(postDetail){
return $http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
});
So you can do
ajaxService.updateTodoDetail(updated_details).success(function(result) {
$scope.result = result //or whatever else.
}
Alternatively you can pass the successfunction into updateTodoDetail:
updateTodoDetail: function(postDetail, callback){
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
})
.success(callback);
So your controller has
ajaxService.updateTodoDetail(updated_details, function(result) {
$scope.result = result //or whatever else.
})
I would prefer the first option so I could handle errors etc as well without passing in those functions too.
(NB: I haven't tested the code above so it might require some modification)

what I usually do is like this
app.factory('call', ['$http', function($http) {
//this is the key, as you can see I put the 'callBackFunc' as parameter
function postOrder(dataArray,callBackFunc) {
$http({
method: 'POST',
url: 'example.com',
data: dataArray
}).
success(function(data) {
//this is the key
callBackFunc(data);
}).
error(function(data, response) {
console.log(response + " " + data);
});
}
return {
postOrder:postOrder
}
}]);
then in my controller I just call this
$scope.postOrder = function() {
call.getOrder($scope.data, function(data) {
console.log(data);
}
}
do not forget to insert the dependency injection of 'call' services into your controller

Related

Cannot get the data in the controller from the service

app.service('customersService', function ($http) {
this.getCustomer = function (id) {
$http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data) {
console.log(data);
return data;
})
};
});
Cannot get the data in the controller from the service
The problem with this code is when i try to run this
customersService.getCustomer(customerID).then
It generates an error mentioned below:
angular.js:13294 TypeError: Cannot read property 'then' of undefined.
The main thing is the call to the service is generated and if i try to print the results on the console in the service the data is there. However i cannot get the data in my controller.
You get that error becuase you are not returning the promise from $http GET request.
Edit your code like this:
app.service('customersService', function ($http) {
this.getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
});
};
});
And then with .then() in your controller, you handle the response data.
app.controller('myController', function($scope, customerService){
customersService.getCustomer(customerID)
.then(function(response){
$scope.data = response;
})
})
You simply forget to return the $http promise that is why undefined is returned. You need to do the following:
...
return $http({ ...
Try given code.
app.service('customersService', function ($http) {
var getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
};
var customersService = {
getCustomer: getCustomer
}
return ProfileService;
});

Angular $http called from service, 'then' is undefined

I have seen this question many times but I can't figure out why one of my controller functions (controller 1) works fine and one (controller 2) doesn't.
Controller 1:
angular.module('app').controller('MyCtrl1',function($scope,MyFactory)) {
//This function works great
MyFactory.deleteItem(item.id).then(function(response) {
//woot woot I am here and I am fine
});
}); //end controller 1
Controller 2:
angular.module('app').controller('MyCtrl2',function($scope,MyFactory)) {
//Function #2 that doesn't work ... 'then' is undefined
MyFactory.createItem(item).then(function(response) {
//booo hooo I never get here and I am definitely not fine
});
}); //end controller 2
The factory:
.factory("MyFactory", function($http) {
var service = [];
service.deleteItem = function(itemId) {
return $http({
method: "delete",
url: "http://www.example.com",
params: //valid params go here
}).then(function(response) {
console.log("DELETING!!!!");
return response.data;
});
}
service.createItem = function(post) {
return $http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).then(function(response){
console.log(response.data); //we are fine here. there is a valid response
return response.data;
});
}
return service;
}); //end factory
The error thrown when executing 'createItem' is 'Cannot read property 'then' of undefined' What am I missing ?
You are missing the return in the createItem statement:
service.createItem = function(post) {
return $http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).then(function(response){
console.log(response.data); //we are fine here. there is a valid response
return response.data;
});
}
Without it, there is no return value (which is undefined) on which you can't chain the .then.
If you are not returning $http the use like this :
$http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).$promise.then(function(response){
console.log(response.data);
return response.data;
});

Factory doesnt return http data response

Im trying to get http post data response using the code below (it is working).
app.factory('LoginService', function($http, $location) {
return {
existUser: function(loginObj)
{
$http({
method: 'POST',
url: server + '/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
data: 'json=' + JSON.stringify(loginObj)
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log(response);
console.log("erro!");
});
}
}
});
Inside of my controller, i have:
LoginService.existUser(loginObj).then(function (data){
console.log(data);
});
And i got the error:
Cannot read property 'then' of undefined
What is wrong?
Your return response.data; returns result of then function, not existUser! Modify your code like below:
app.factory('LoginService', function($http, $location) {
return {
existUser: function(loginObj)
{
return $http({
method: 'POST',
url: server + '/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
data: 'json=' + JSON.stringify(loginObj)
})
}
}
});
In this case, existUser method returns promise object, that has .then method

Angular js is controller not loading

I have loaded a page using AngularJS. I have the following code:
var app = angular.module("adhocAnalytical",[]);
app.controller(
"ReportController",
function ($scope,$http) {
$http({
method: 'POST',
url: '/campustoolshighered/k12_reports_adhocreport4_analytical_body.do',
data: 'action=fetchinitdata',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
$scope.questions = response;
});
}
);
angular.element(document).ready(function (){
angular.bootstrap(document,['adhocAnalytical']);
});
When we load a page second time in a current session using AngularJS, it does not load. It give only the expression written on the jsp page such as:
{{question.title}}
{{cell.f}}{{cell.f}}
{{row.h}} {{row.v}} {{row.v}}
Remove }; after the success callback:
app.controller(
"ReportController",
function ($scope,$http) {
$http({
method: 'POST',
url: '/campustoolshighered/k12_reports_adhocreport4_analytical_body.do',
data: 'action=fetchinitdata',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
$scope.questions = response;
});
}
);

how to change post['Content-Type'] in angularjs

i want to change post['Content-Type'] in angularjs so i use
app.config(function($locationProvider,$httpProvider) {
$locationProvider.html5Mode(false);
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
and the event is
$http.post("http://172.22.71.107:8888/ajax/login",{admin_name:user.u_name,admin_password:user.cert})
.success(function(arg_result){
console.log(arg_result);
});
};
however the rusult is
Parametersapplication/x-www-form-urlencoded
{"admin_name":"dd"}
what i want is
Parametersapplication/x-www-form-urlencoded
admin_name dd
so what i should do?
Try like:
var serializedData = $.param({admin_name:user.u_name,admin_password:user.cert});
$http({
method: 'POST',
url: 'http://172.22.71.107:8888/ajax/login',
data: serializedData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}}).then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
angular.module('myApp', [])
.config(function ($httpProvider) {
$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
})
OP is using Content-Type : application/x-www-form-urlencoded so you need to use $httpParamSerializerJQLike to change post data from JSON to string
note: there is no data property but is params property
$http({
method: 'POST',
url: 'whatever URL',
params: credentials,
paramSerializer: '$httpParamSerializerJQLike',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Additionally, you can inject the serializer and use it explicitly with data property
.controller(function($http, $httpParamSerializerJQLike) {
....
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
Have a look at this:
How can I post data as form data instead of a request payload?
Alternatively, you could do the following:
$http.post('file.php',{
'val': val
}).success(function(data){
console.log(data);
});
PHP
$post = json_decode(file_get_contents('php://input'));
$val = print_r($post->val,true);

Resources