How to accept more than one HTTP object in Angular.js? - angularjs

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

Related

AngularJS scope variable undefined in page load for other function

Im trying to get initialize the scope variable via http get request in page load in first function but then when trying to use the scope variable in other function in the same page load, it is undefined.
app.controller('GradeAndSectionCtrl', function ($scope, $http) {
$scope.GetCategories = function () {
$http({
method: 'GET',
url: '/GradeAndSection/GetCategories'
}).then(function (response) {
$scope.categories = response.data;
if (response.data != null) {
$scope.drpCategory = $scope.categories[0].categoryID;
}
});
};
$scope.GetGrades = function () {
\\$scope.drpCategory; here; is; undefined;
$http({
method: 'GET',
url: '/GradeAndSection/GetGrades?categoryID=' + $scope.drpCategory
}).then(function (response) {
$scope.grades = response.data;
});
};
$scope.GetCategories();
$scope.GetGrades();
});
You are making asynchronous call using promises in your code therefore $scope.drpCategory may not be loaded when you call GetGrades function. You can call your GetGrades function when GetCategories is resolved.
$scope.GetCategories = function () {
$http({
method: "GET",
url: "/GradeAndSection/GetCategories"
}).then(function (response) {
$scope.categories = response.data;
if (response.data != null) {
$scope.drpCategory = $scope.categories[0].categoryID;
$scope.GetGrades();
}
});
}
Try to call the function GetGrades in then()
$scope.GetCategories = () => {
$http
({
method: 'GET',
url: 'categories.json',
})
.then(data => {
$scope.categories = data.data;
$scope.drpCategory = $scope.categories[0].category
$scope.GetGrades($scope.drpCategory)
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
}
$scope.GetGrades = (drpCategory) => {
$http
({
method: "GET",
url: "categories_" + drpCategory + ".json"
}).then(function (response) {
$scope.grades = response.data;
console.log($scope.grades)
});
}
$scope.GetCategories()
Working example: http://plnkr.co/edit/ZN8nI7OhAyWiJWlqeJsU?p=preview

$http return response - 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?

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 enabling paging from a local json file

I am trying to set up a service that, when I feel like it, I can flip to live data coming from an API. The getData function takes skip/take parameters to define start record and number of records.
My data is currently in a json file:
{
"Data":[{
"Id":"1462",
"Name":"Cynthia"
},{
"Id":"1463",
"Name":"Bob"
},{
...
}],
"Total":71
}
My service currently pulls all json data at once:
var _getData = function (optionsData) {
return $http({
method: 'GET',
url: 'data/packages.json'
})
.then(function successCallback(response) {
return response;
},
function errorCallback(response) {
return response;
});
}
It seems to me that I have to write the paging logic right into the service:
.then(function successCallback(response) {
var records = response.data.Data;
var firstRecord = 0;//optionsData.skip;
var numberOfRecords = 1;//optionsData.take;
response.data.Data = records.slice(firstRecord, firstRecord + numberOfRecords);
return response;
},
Is this the right way in principle?
[ UPDATE ] The controller method:
var getPackageData = function (options){
return dataService.getData(options.data).then(
function successCallback(response) {
options.success(response.data.Data);
$scope.totalCount = response.data.Total;
},
function errorCallback(response) {
// handle error
}
);
};
my errorCallback is wrong? How?
The errorCallback is converting a rejected promise to a fulfilled promise.
To avoid conversion, either throw the response or return $q.reject:
var _getData = function (optionsData) {
return $http({
method: 'GET',
url: 'data/packages.json'
})
.then(function successCallback(response) {
return response;
},
function errorCallback(response) {
//To avoid converting reject to success
//DON'T
//return response;
//INSTEAD
throw response;
//OR
//return $q.reject(response);
});
}
Another common error is to fail to include either a throw or return statement. When a function omits a return statement, the function returns a value of undefined. In that case, the $q service will convert rejected promises to fulfilled promises which yield a value of undefined.

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