How to know all HTTP requests sendable by an Angular application? - angularjs

Is It possible generating a sort of documentation,
where are addressed all HTTP requests sendable by a specific Angular Application?

try to store the url addresses into an array and then loop the HTTP request call.
Something like this maybe:
for (var i=0 ; i < $scope.urls.length ; i++)
{
$http.get($scope.urls[i])
.success(function(response){
$scope.results[i] = response.data;
})
.error(function(response){
$scope.errors[i] = response.error;
$scope.errormessages[i] = response.errormessage;
});
}
And using scope.$evalAsync(function () {}) if needed to synchronous the call.

Related

How do I know that all my $http GET requests are completed?

Using AngularJs 1.6.5 I am making multiple $http GET calls using the for loop. Here is the code:-
for(var i=0; i < 11; i++){
var url = "/api/learner_qa/" + i;
$http.get(url).then(successCallback, errorCallback);
function successCallback(response){
console.log(response);
};
function errorCallback(error){
console.log(error);
};
};
What I want to do is trigger a function when all the GET requests are completed.
I referred to answer posted here and want to know how can this be done on an array as in my case?
The time will likely arise where you need to resolve multiple promises
at once, this is easily achieved through $q.all() by passing in either
an Array or Object of promises which will call .then() once both are
resolved:
You can take an array and push your http calls into it
var array = [];
for(var i=0; i < 11; i++){
var url = "/api/learner_qa/" + i;
array.push($http.get(url))
};
$q.all(array).then(function(response) {
console.log(response)
}).catch(function(error){
console.log(error)
});
Using this code, the response will come once all your requests are successful.
Here is an example documentation

Use response from one $http in another $http in Angularjs

First of all I want to use $http in order to receive some data (e.g. students), then I want to make another $http call to get e.g. studentDetails. After that I want to append some part of studentDetails to students JSON.
Also I need response from the first call in order to create the url for the second call.
Problem is that I cannot access response of the first http call inside the another.
Does anybody know how this can be done?
var getStudents = function(){
var deferred = $q.defer();
$http.get("https://some_url")
.success(function(response){
deferred.resolve(response);
}).error(function(errMsg){
deferred.reject(errMsg);
});
return deferred.promise;
}
var appendStudentDetails = function(){
getStudents().then(function(response){
var studentsWithDetails = response;
for(var i=0; i<studentsWithDetails.length; i++){
$http.get("some_url/"+studentWithDetails[i].user.details+"/")
.success(function(res){
//here I want to append the details,
//received from the second http call, to each student
//of the array received from the first http call
//PROBLEM: I cannot access response of the
//first http call inside the another
})
}
})
You're using the deferred anti-pattern as well as the deprecated success/error-callbacks. You should instead use then, since it returns a promise, and you can chain promises.
Here's an example of how you could do it:
function getStudents(){
return $http.get('[someurl]');
}
function appendStudentDetails(studentsWithDetails){
for(var i=0; i<studentsWithDetails.length; i++){
appendSingleStudentDetails(studentsWithDetails[i]);
}
}
function appendSingleStudentDetails(singleStudent){
$http.get("some_url/"+singleStudent.user.details+"/")
.then(function(res){
// Append some stuff
singleStudent.stuff = res.data;
});
}
// Call it like this:
getStudents()
.then(function(response){ return response.data; })
.then(appendStudentDetails);
I decided to structure the appendStudentDetails function a little differently, based on its name, but you could as easily just call getStudents() within the method as you did before.
Beware not to use the i-variable inside your inner then-function, as that would cause you troubles with closure.
Edit: Fixed example to avoid problem with i being under closure.

How do you pass in HTTP headers to make a request from an API?

Using Angular, I'm trying to pass in HTTP headers with the request, “App-Id” and “App-Key” to get data from this API.
I tried setting the headers like this:
$http.defaults.headers.common["App-Id"] = '5a3d8b8d';
$http.defaults.headers.common["App-Key"] = '738e9aca62e7465446b7be8fe4219ffa';
but I got a Response for preflight is invalid error.
http://jsfiddle.net/9Ymvt/4573/
Adding Headers to an $http Request on a Per Request Basis
To add headers to a $http request on a per request basis, add them to the headers property of the $http config object.
var xheaders = {};
xheaders["App-Id"] = '5a3d8b8d';
xheaders["App-Key"] = '738e9aca62e7465446b7be8fe4219ffa';
var xurl = 'https://uk.bookingbug.com/api/v1';
var configObj = { method: 'GET',
url: xurl,
headers: xheaders
};
$http(configObj)
.then(function onFulfilled(response) {
console.log(response);
vm.headers = response.config.headers;
vm.data = response.data
}).catch( function onRejection(errorResponse) {
console.log("Error: ", errorResponse.status);
console.log(errorResponse);
vm.error = errorResponse;
})
;
The code was getting pre-flight errors because it was using the incorrect URL. The correct base URL is https://uk.bookingbug.com/api/v1 which supports App-Id headers and CORS.
The DEMO on JSFiddle.
I do not think this is a complete answer to your question, but here is what I have in my project:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
// code for routes
});
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
This solves my problem with CORS. If you want to do another type of header, you probably can find your answer here.
Preflight errors are related to CORS. You might want to look at rack-cors to enable cross-site api calls via javascript. There is a manual configuration here: https://gist.github.com/dhoelzgen/cd7126b8652229d32eb4

How to pass multiple parameters in a URL Angular/REST API

I'm trying to pass multiple parameters in a URL with no luck. I'm not sure if it makes a difference but I am doing it through Angular. I'm trying to send the request to a REST API backend that I know works for single requests. Here is what my backend looks like
index.js
var express = require('express');
var router = express.Router();
var game = require('./game');
router.get('/api/v1/gameRefined/:from_datepicker:to_datepicker:from_timepicker:to_timepicker:selectLevel', game.getAllRefined);
module.exports = router;
game.js
...dbconnection stuff...
var game={
getAllRefined: function(req, res) {
var refines = req.params;
console.log("getting refined games");
pool.getConnection(function(err, connection){
var query = connection.query('SELECT * FROM game WHERE date >= ? AND date <= ? AND time >= ? AND time <= ? and level = ?', [refines.from_datepicker, refines.to_datepicker, refines.from_timepicker, refines.to_timepicker, refines.selectLevel], function(err, rows) {
connection.release();
if(err) {
throw err;
}else{
res.json(rows);
}
});
})
},
}
module.exports = game;
I send the request from this factory
.factory('gameFactory', ['$http',
function($http) {
var _gameFactory = {};
_gameFactory.getRefinedGames = function(dateFrom,dateTo,timeFrom,timeTo,level) {
var encodedParam = encodeURIComponent(baseUrl + '/api/v1/gameRefined/?from_datepicker='+dateFrom+'&to_datepicker='+dateTo+'&from_timepicker='+timeFrom+'&to_timepicker='+timeTo+'&selectLevel='+level+'');
return $http.get(encodedParam);
}
return _gameFactory;
}])
That sends this request that comes back as a 404:
http://localhost:8100/http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fv1%2FgameRefined%2F%3Ffrom_datepicker%3D2015-02-05%26to_datepicker%3D2015-02-19%26from_timepicker%3D12%3A00%26to_timepicker%3D18%3A00%26selectLevel%3D1
I have tried it encoded and not encoded, with forward slashs, with semi colons, but nothing has worked so far.
I don't know why a localhost gets appended at the start, but even trying it in postman without the first localhost still is a 404 error.
How should I be doing this? Any help is appreciated. Thank you.
First, other than separating the work into a factory, you aren't really using Angular here. Second, I would consider posting to your API, return JSON results from the API, and then use a promise to read the data back into Angular.
Use $http.post
Let Angular do this work for you. Something like the below will generate the URL request for you. The return value of $http is also a promise, so using .success and .error will allow you to parse any returned data as well, even if it is just a success or failure message - but it is a great method of passing data between server/API and client.
.factory('gameFactory', ['$http',
function($http) {
return {
reachAPI: function(dateFrom, dateTo) {
$http.post('http://localhost:8080/api/v1', {
'dateFrom': dateFrom,
'dateTo': dateTo
})
.success(function(data, status, headers, config) {
*things happen*
data.somethingReturned // from your API
});
}
}]);
Consider body-parser
I know you said you have confidence in your REST API structure, but body-parser is an Express middleware that can parse URL-encoded strings and may prove helpful in reading your data. Personally, I think it lends towards more readable code.
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
router.route('/api').post(function(req, res) {
*things happen*
req.body.dateFrom //find your data
*things happen*
res.json(returnedData);
});
Hope that helps

Angular js api url in loop

$http({method: 'GET', url: '/xxx/xxx/xas'}).success(function(data) {
$scope.website = data.websites;
});
$http({method: 'GET',url: '/xx/xasxxx?websiteId='+$scope.website.websiteId}).success(function(data) {
$scope.onlinedata1 = data.coupons;
});
I try to get websiteID from top url and pass that id in to 2nd url .my json data structure
"websites":[{
"websiteName":"Flipkart",
"websiteId":"1",
},
{
"websiteName":"asas",
"websiteId":"5",
}]
Try to pass every id one by one. I am using AngularJS v1.2.17.
Move the second HTTP call within the success callback of the first one:
$http({method: 'GET', url: '/xxx/xxx/xas'}).success(function(data) {
$scope.website = data.websites;
for (var i = 0; i < data.websites.length; i++)
{
$http({method: 'GET',url: '/xx/xasxxx?websiteId='+data.websites[i].websiteId}).success(function(data) {
$scope.onlinedata1 = data.coupons;
});
}
});
This can be simplified considering that your requests are GETs:
$http.get('/xxx/xxx/xas')
.then(function(res) {
for (var i = 0; i < res.data.websites.length; i++)
{
$http.get('/xx/xasxxx?websiteId='+res.data.websites[i].websiteId)
.then(function(res) {
$scope.onlinedata1 = res.data.coupons;
});
}
});
Please note that the above will issue one request for each website returned by the API. If you have control over the API you might want to consider accepting multiple website IDs on the second URL resource (/xx/xasxxx?websiteIds=1,5,7,12,56) so as to limit the number of requests issued by the client.
Use $q - service in module ng
A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

Resources