$http return response - AngularJS - angularjs

I need to create service in AngularJS to return the response of HTTP requests. My problem is the asynchronous request, because after I've submitted the request, my function returns undefined instantly and does not return the response from the server.
app.service('TesteService', function($http) {
this.teste = function(data) {
var data = "*";
$http({
method: 'GET',
url: 'teste-s.php',
params: {data: "bem recebido"}
}).then(function successCallback(response) {
data = response.data;
alert(data);
return data;
}, function errorCallback(response) {
data = "500";
});
}
});
How do I fix this?

Related

View not loading new data after http request in angularjs

I want to submit data from a form and display the result in the view directly after http request returns a result. But it's not happening.
$scope.formData = {};
$scope.add = function (){
$http.post('add.php',$scope.formData,{'Content-Type': 'application/x-www-form-urlencoded'})
.then(function (result) {
console.log(result.data);
if (result){
$scope.data = result.data;
}
});
};
And this is add.php. In this file I just want to return the posted data in json.
function index(){
$data = $this->input->post();
echo json_encode($data);
}
I find it returns false value. I wonder how I process data submitted with post method using $http.post like this.
You can try this way to pass data to add.php service
$scope.add = function (){
$http({
method: 'POST',
url: 'add.php',
headers: {
'Content-Type': application/x-www-form-urlencoded
},
data:$scope.formData
}).then(function successCallback(response) {
$scope.data = response.data.data;
}, function errorCallback(response) {
console.log(response);
});
}
Try this in PHP:
$data = $this->input->post(NULL, TRUE);
In AngularJS, inject $httpParamSerializerJQLike in your service/factory
$scope.add = function (){
$http({
method: 'POST',
url: '/add.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializerJQLike($scope.formData);
}).then(function resolve(response) {
console.log(response);
$scope.data = response.data.data;
}, function reject(response) {
console.log(response);
});
}

Angular 1.5 - passing http post response to controller

I am trying to pass an http response from my controller to a service, it works well except for getting the response to go into the controller here is my code below:
For my service
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload,callBack){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function successCallback(callBack){
console.log(callBack);
return deferred.resolve(callBack);
}, function errorCallback(callBack){
//deferred.reject(error);
console.log(callBack);
return deferred.reject(callBack);
});
return deferred.promise;
}
}
});
and for the Controller
app.controller('LoginCtrl', function($scope,$position,$rootScope,$state,ApiService) {
$scope.forms = {
'loginForm':''
}
var payload ={
'username':'',
'password':''
}
$scope.userLogin = function(form){
$scope.username = form.username.$modelValue;
$scope.password = form.password.$modelValue;
payload ={
"username":$scope.username,
"password":$scope.password
}
ApiService.login(payload, function(result){
console.log(result);
}
});
Now I don't understand because when I console.log() the response I'm able to see it in the service but doing the same on the controller I'm getting nothing.
No need to make it complex. Simply return promise from factory and use it in controller.
factory:
app.factory('ApiService',function($http,Config,$q) {
return {
login: function(payload) {
return $http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
});
}
}
});
in controller :
ApiService.login(payload).then(function(data){
// use response data
}, function(error) {
// handle error
});
You should use it like this:
ApiService.login(payload).then(function(result){
console.log(result);
});
Because you are returning a promise in your service.
Also you don't need that callback parameter, because the then method on the promise is your callback when it finishes and you can access the data your resolve it with.
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function (result){
return deferred.resolve(result);
}, function (result){
return deferred.reject(result);
});
return deferred.promise;
}
}
});

Get value out of Json return

My angularJs function returns response in Json, but I am not been able to get the 'model' part out from it.
Below is my code:
this.search = function () {
var response = $http({
method: 'GET',
url: '/api/TalentPool/Search'
});
return response;
}
this.search().then(function (response) {
console.log('conscole: ' + response.data.model)
})
this.search().then(function (response) {
console.log(response.data.model)
})
And below is my mvc method:`
List<CandidateSearchViewModel> output = CRBuilderObj.ContructResultsViewModel(data);
CandidateSearch.model = output;
CandidateSearch.baseCriteria = criteria;
return Ok(CandidateSearch);
if you want to access the response of the http request then you have to resolve the promise firs. then access the model property from the response
this.search = function () {
return $http({
method: 'GET',
url: '/api/TalentPool/Search'
});
}
//resolve the promise like this
this.search().then(function(response){
console.log(response.data.model)
})

functions executed before angular http success response

Am trying to hit web service with a directive controller, I hit the post method and got the response, but values I expected are become empty because all compiled before the success response.
This is my controller within the directive
controller: ['$scope', '$http', 'popupService','SessionUtils', function($scope, $http, popupService,SessionUtils) {
$scope.responseValue = "";
$scope.sendCSVFile = function(link, fileData) {
$scope.seriveResponse = $http({
method: "POST",
url: link,
data: fileData,
headers: {
'Content-Type': undefined
}
}).success(function(response) {
if(response.status == "FAILURE"){
popupService.showErrMsg(response.message);
return false;
}
else {
$scope.responseValue = response;
//SessionUtils.updateResponse(response);
var success = "File Uploaded Successfully";
popupService.showSuccessMsg(success);
return response;
}
return $scope.responseValue = response;
});
});
and I called the controller from the directive link function like
var res = scope.sendCSVFile(attrs.getUrlModel, formData);
scope.gridUpdate(res);
the value res returning undefined, but I get the response after I binded the res. How to I get the promising response and execute the function after.!
You can get promise, not standard data, ajax is asynchronous call, so change code to:
$scope.sendCSVFile = function(link, fileData) {
return $http({ //return promise object
method: "POST",
url: link,
data: fileData,
headers: {
'Content-Type': undefined
}
}).success(function(response) {
if(response.status == "FAILURE"){
popupService.showErrMsg(response.message);
return false;
}
else {
$scope.responseValue = response;
//SessionUtils.updateResponse(response);
var success = "File Uploaded Successfully";
popupService.showSuccessMsg(success);
return response;
}
return $scope.responseValue = response;
});
});
usage:
$scope.sendCSVFile(attrs.getUrlModel, formData).then(function(response){
//here ajax is completed and in response variable You have raturn from success callback
if (response)
scope.gridUpdate(response);
});

Access successCallback in AngularJs $http Method

I want to access to response successCallback(response)
var list_of_user = $http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.all_users = response.data;
}, function errorCallback(response) {
console.log(response);
});
console.log("$scope.all_users ", $scope.all_users)
is undefiend
I can access $scope.all_users from html, but how can I access to $scope.all_users in controller?
$http is async and console.log is executed before actually request is completed.
As you defined in comment that you want to compare two responses you can do that by simply putting a flag that will wait for both requests to finish.
var done = 0;
var onRequestFinishes = function() {
done += 1;
if (done < 2) {
return; // one of both request is not completed yet
}
// compare $scope.response1 with $scope.response2 here
}
and send first request and save response to $scope.response1 and invoke onRequestFinishes after that.
$http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.response1 = response.data;
onRequestFinishes();
}, function errorCallback(response) {
console.log(response);
});
Similarly send second request
$http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.response2 = response.data;
onRequestFinishes();
}, function errorCallback(response) {
console.log(response);
});
For request handling you can create individual promise chains and use $q.all() to execute code when all promises are resolved.
var request1 = $http.get('/users/').then(function(response)
{
console.log('Users: ', response.data);
return response.data;
}
var request2 = $http.get('/others/').then(function(response)
{
console.log('Others: ', response.data);
return response.data;
}
$q.all([request1, request2]).then(function(users, others)
{
console.log('Both promises are resolved.');
//Handle data as needed
console.log(users);
console.log(others);
}

Resources