How to get request url in an angularjs $http request - javascript

I have this request:
$http({
method: 'get',
url: '/api/items/',
params: {a: 1, b: 2, c: 3}
}).success(function (response) {
console.log(response);
}).error(function (err) {
console.log(err);
});
Is there a way, to fetch the url it used to make the request after the request has been made(in the callback or otherwise)?
I would want the output:
http://www.example.org/api/items?a=1&b=2&c=3
Here the same thing is done with jquery.

The success handler gets 4 parameters passed into it:
$http
.get({ url: '/someUrl', params: { q: 3 } })
.success(function(data, status, headers, config) {});
The fourth parameter config has the following properties:
{
method: "GET",
url: {
url: '/someUrl',
params: {
q: 3
}
}
}
You can use window.location.origin to get the base url and build a simple function to concat it all together.
This function should yield the expected response:
var baseUrl = window.location.origin;
var query = [];
Object.keys(config.url.params || {}).forEach(function (key) {
var val = config.url.params[key];
query.push([key, val].join('=')); // maybe url encode
});
var queryStr = query.join('&');
var fullPath = baseUrl + config.url.url + '?' + queryStr;
Unfortunately, this function will only work as long as the parameters are passed in the format described above. If you pass them in a different format, you'll have to modify this function a bit. You can use this as a playground.
Afaik, there is no simpler way. At least a feature request exists.
See the docs of $http for reference

This config parameter of the callback has the url as a property:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
console.log(config.url);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Based on: https://docs.angularjs.org/api/ng/service/$http

You can use http request Interceptor.
Configure the Interceptor in config function using $httpProvider
Whrein for request Interceptor you can able to see the URL and params that you passed with URL prior to making the request

try just looking at the XHR Request urls in your browser dev tools

Related

Calling RESTful apis through ajax and angular js

If the URL that is to be hit has to be passed variables i.e.
API.openweathermap.org/data/2.5/forecast/city?name=[random_city_name]&APPID=[key_value],
then what is better to use ajax or angular js.
If I am using ajax then how am I supposed to pass the variable? I am a newbie in this. So, need your help.
Your url seems to have request parameters and assuming you are using angular1
For this, you can use
$http({
method: 'GET',
url: url,
headers: {},
params : {}
})
Put your parameters as a map and $http will take care of creating an url.
Refer $http documentation here
what is better to use ajax or angular js
You can't compare as AJAX provides a way to communicate (send requests and get responses) with the server asynchronously and AngularJS used AJAX to extends the 2-way data binding.
To accomplish the above situation we can use Angular $http service.
var baseUrl = API.openweathermap.org/data/2.5/forecast/city;
var method = 'GET';
var data = {};
var params = {
"name":cityName,
"APPID":key_value
};
$http({
method: method,
url: baseUrl,
params : params,
data : data
}).then(function mySucces(response) {
$scope.data = response.data;
}, function myError(response) {
$scope.data = response.statusText;
});
You can use angular $http service and pass your params like below.
var UserInfo = function() {
$scope.userID = "1111";
var req ={
"method":"GET",
"url": someURL + $scope.userID,
"withCredentials":true
};
$http(req).then(function(response) {
alert('success');
}, function(response) {
alert('error');
});
};

AngularJS - Dynamic URL with ID

config.js
angular.module('config', []).constant('ENV',
{
name: 'My Angular Project',
apiEndPoint: 'http://SOMEIP/myServer', //API host,
adminUrl:'/admin/regionid/site/siteid/admin/regionid', //endpoint
loginUrl:'/login/regionid/site/siteid/device'
});
controller.js
this.userLogin = function(username, password) {
var adminServicePath = ENV.apiEndPoint + ENV.adminUrl
//final url = http://SOMEIP/myServer/admin/1/site/1/admin/1
var loginServicePath = ENV.apiEndPoint + ENV.loginUrl
//final url = http://SOMEIP/myServer/login/2/site/2/device
return $http({
method: 'POST',
url: adminServicePath,
headers: {
"Authorization": "Basic ",
"Content-Type": "application/x-www-form-urlencoded"
}
})
};
Here I am appending API with endpoint to form a complete URL. My issue is regiondid and siteid are dynamic. After user logs in, one REST API request will fetch siteid and regionid in response.
How do I dynamically replace siteid and regionid in URL with ID's
received in API response? After receiving id's in response, call a function that replaces the value.
You can use the String.prototype.replace(substr, newsubstr)
You can keep regionID instead of ?
var ENV = {
name: 'My Angular Project',
apiEndPoint: 'http://SOMEIP/myServer', //API host,
adminUrl: '/admin/?/site/?/admin/?', //endpoint
loginUrl: '/login/?/site/?/device'
};
var adminServicePath = ENV.apiEndPoint + ENV.adminUrl.replace("?", 1).replace("?", 1).replace("?", 1);
console.log("Final url admin : " + adminServicePath);
var loginServicePath = ENV.apiEndPoint + ENV.loginUrl.replace("?", 2).replace("?", 2);
console.log("Final url login : " + loginServicePath);
instead of constant, you can use value.
angular.module('config', []).value('ENV',
{
name: 'My Angular Project',
apiEndPoint: '', //API host,
adminUrl:'', //endpoint
loginUrl:''
});
Inject ENV and set all values after API call.
ENV.name = xyz;
ENV.apiEndPoint = xyz;
ENV.adminUrl = xyz;
ENV.loginUrl = xyz;
but the values might get set to default once you refresh the browser.
I'll assume that the siteid and the regionid can only be obtained from the response to the login endpoint.
Using a constant might not be the best idea here for obvious reasons (i.e. they're constant, and can't be created at the time you want to create them).
Instead, you could do one of a few things - a simple solution that probably works for a lot of use cases would be to create a login service that wraps your API call and then sets a value either in the service or another service that can be injected into wherever you need it.
It might look like this:
angular.module('app')
.service('loginService', function($http) {
var siteId,
regionId;
function login(username, password) {
return $http({
method: 'POST',
url: '<login endpoint here>',
headers: {
"Authorization": "Basic ",
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(function(result) {
siteId = result.siteId;
regionId = result.regionId;
});
}
);
This makes the values available to you any time you need to make an API call after logging in. However, this isn't great since you will need to inject the loginService into any controller/service that needs it, and that controller/service might not really care about the login service at all.
An improved approach to this could be to have an API service that performs the http gets/sets/puts/posts/whatever and that is accessed by your data access layer. Inside this service, you can set/get the siteid and regionid.
It might look like this:
angular.module('app')
.service('api', function($http) {
var siteId,
regionId;
var defaultHeaders = {
"Authorization": "Basic ",
"Content-Type": "application/x-www-form-urlencoded"
};
function post(url, options) {
return $http({
method: 'POST',
url: url,
headers: options.headers ? options.headers : defaultHeaders
});
}
// Other functions to perform HTTP verbs...
});
angular.module('app')
.service('loginService', function(api) {
function login(username, password) {
api.post('urlHere', options)
.then(function(result) {
api.siteId = result.siteId;
api.regionId = result.siteId;
});
}
});
You can then access the siteid and regionid where you like.
For example:
angular.module('app')
.controller('someService', function(api) {
function doSomethingWithTheApi() {
var url = 'www.google.com/' + api.siteId + '/' + api.regionId + 'whatever-else';
return api.post(url, {});
}
);
Note: the code above isn't complete, but it gives you a very good idea of the approach you could take that is reasonably clean, not too hacky and is easily testable :)
Hope that helps!

AngularJS - get headers in response

I'm doing a $http.get request to a https service which has an XML file and it need the headers('Content-length') to know it size.
This's my code:
$http({
method : "GET",
url : "https://url.com/xml_file.xml"
}).then(
function sCallback(data, status, headers, config, statusText) {
console.log( headers('Content-Length') );
}, function eCallback(data, status, headers, config, statusText) {
$log.warn(data, status, headers, config, statusText);
});
The result of the request is: "headers is not a function".
Is there another way to get it?
console.log( data.headers('Content-Length'));
console.log( data.headers('Content-type'));

angularJS: http request configuration url must be a string

I have a function that takes an input from the front-end, and then concatinates that input into an URL that I want to get from wikipedia. Since I had problems with CORS, I implemented my $http.get as JSONP, and now I get the following error:
angular.js:13236 Error: [$http:badreq] Http request configuration url
must be a string. Received:
{"method":"JSONP","url":"https://en.wikipedia.org/w/api.php?action=query&format=json&uselang=user&prop=extracts%7Cpageimages&titles=Maya+Angelou&piprop=name%7Coriginal"}
The thing is, that his error shows the concatinated url as a string?
Can anybody point out what I'm doing wrong?
This is the function I am calling:
//function to get author info from wikipedia
$scope.getAuthorInfo = function(author) {
//remove whitespace from author
author = author.replace(/\s/g, '+');
//concat the get URL
var url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&uselang=user&prop=extracts%7Cpageimages&titles=' +
author + '&piprop=name%7Coriginal';
//get author info from wikipedia
$http.get({
method: 'JSONP',
url: url
})
.then(function successCallback(response) {
$scope.author = response.data;
//for every result from wikipedia, trust the extract as html
for (var x in $scope.author.query.pages) {
$scope.author.query.pages[x].extract = $sce.trustAsHtml($scope.author.query.pages[x].extract);
}
}, function errorCallback(response) {
console.log(response);
});
};
If you need additional information, please let me know.
$http({
method: 'JSONP',
url: url
}).then(function successCallback(response) {
// ok
}, function errorCallback(response) {
// ko
});
$http.get is a shortcut method for $http({ method: 'GET' }), and expects the URL as the first parameter.
As you're using JSONP, you could also use the $http.jsonp shortcut:
$http.jsonp(url).then(function successCallback(response) {
// ok
}, function errorCallback(response) {
// ko
});

How can I replace $resource with $http in AngularJS?

My application has the following $resource calls. From what I can see this could be replaced with $http.
$resource('/api/:et/', { et: $scope.data.entityType })
.save(data, newSuccess, error)
.$promise.finally(last);
$resource('/api/:et/:id', { et: $scope.data.entityType })
.delete({ id: entityId }, deleteSuccess, error)
.$promise.finally(last);
$resource('/api/:et/:id', { et: $scope.data.entityType }, { update: { method: 'PUT' } })
.update({ id: entityId }, data, editSuccess, error)
.$promise.finally(last);
I have checked the $http documentation but I cannot see how to add the calls to the xxxSuccess, error functions and how to do the .$promise.finally(last).
Can someone explain how I could replicate this functionality using $http ?
$http is for general purpose AJAX. In most cases this is what you'll be using. With $http you're going to be making GET, POST, DELETE type calls manually and processing the objects they return on your own.
$resource wraps $http for use in RESTful web API scenarios.
Syntax
$http({
method : 'GET',
url : '/someUrl',
param : { paramKey : paramValue}, // optional
headers : 'someHeaders' // optional
}).success(function(data, status, headers, config)
{
// this callback will be called asynchronously
// when the response is available
}).error(function(data, status, headers, config)
{
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$http Documentation - https://docs.angularjs.org/#!/api/ng/service/$http
Maintaing Promise in $http
app.factory('myService', function($http) {
var myService = {
async: function() {
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http.get('/someUrl').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
return response.data;
});
// Return the promise to the controller
return promise;
}
};
return myService;
});
app.controller('MainCtrl', function( myService,$scope) {
// Call the async method and then do stuff with what is returned inside our own then function
myService.async().then(function(d) {
$scope.data = d;
});
});
Take a look at this article Angular Promises, It will definitely benifit you in acheving such scenerios.
$resource is a further abstracted version of $http. If you are already using $response you may find it's not useful to change your logic to use $http. That said -
https://docs.angularjs.org/api/ng/service/$http
General usage
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Categories