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);
}
Related
I have the following code:
$scope.simulate = function() {
$http({
method: 'GET',
url: 'http://localhost:3000'
}).then(function successCallback(response) {
$scope.fileContent = response;
// simulationData.addData($scope.fileContent);
},
function errorCallback(response) {
$scope.fileContent = response;
});
}
I am trying to make it so that this code runs in a loop and is constantly checking for a new HTTP Object at the specified URL. I am unfamiliar with Angular.js and would appreciate the help.
anuglarjs offers the interval service that you could use here, inject it and use like:
$scope.simulate = function() {
return $interval(function() {
$http({
method: 'GET',
url: 'http://localhost:3000'
}).then(function successCallback(response) {
$scope.fileContent = response;
// simulationData.addData($scope.fileContent);
}, function errorCallback(response) {
$scope.fileContent = response;
});
}, 5000); // whatever interval you want here
}
then you can cancel the interval by calling $interval.cancel(param) where param is the return value of the function
like so:
var interval = $scope.simulate();
$interval.cancel(interval);
I can't access the output variable from my 1st http get request, i need this data for another http Post request.
None.
$scope.submit = function(x) {
$http({
method: "GET",
url: url + 'getOSchild',
params: { ncard: x }
}).then(function success(response) {
$scope.osChild = response.data;
console.log($scope.osChild) // this has an output
}, function error(response, status) {
console.log(response)
console.log(status)
});
$http({
method: "POST",
url: url + 'printOS',
data: JSON.stringify({
CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: $scope.osChild //this is null
}),
header: {
'Content-Type': 'application/json'
},
}).then(function success(response) {
console.log(response)
}, function error(response, status) {});
}
I need the $scope.osChild to be present in my http post request.
Simply chain the two XHRs:
function getOSChild (x) {
return $http({
method: "GET",
url: url+'getOSchild',
params: {ncard: x}
}).then(function success(response) {
$scope.osChild = response.data;
console.log($scope.osChild); // this has an output
return response.data;
},function error(response) {
console.log(response)
console.log(response.status);
throw response;
});
}
$scope.submit = function(x) {
getOSChild(x).then(function(osChild) {
$http({
method: "POST",
url: url+'printOS',
data:{ CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: osChild //chained
}
}).then(function success(response) {
console.log(response)
});
});
};
The .then method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining.
For more information, see
AngularJS $q Service API Reference - chaining promises
You're Missing the Point of Promises
first GET call is asynchronous so $scope.osChild setting null initially. so suggestion is to use Promises https://ng2.codecraft.tv/es6-typescript/promises/
$scope.getOSChild = function() {
var deferred = $q.defer();
$http.get(url + 'getOSchild')
.then(function onSuccess(response) {
$scope.osChild = response.data;
deferred.resolve(response.data);
}).catch(function onError(response) {
console.log(response.data);
console.log(response.status);
deferred.reject(response.status);
});
return deferred.promise;
};
$scope.submit = function(x) {
$scope.getOSChild().then(function (osChild) {
$http({
method: "POST",
url: url + 'printOS',
data: JSON.stringify({
CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: osChild
}),
header: {
'Content-Type': 'application/json'
},
}).then(function onSuccess(response) {
console.log(response);
}, function onError(response, status) {});
});
};
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?
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);
});
}
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;
}
}
});