Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get request url in an angularjs $http request

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.

like image 805
Jahongir Rahmonov Avatar asked Nov 01 '22 00:11

Jahongir Rahmonov


1 Answers

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

like image 77
riptidebyte Avatar answered Nov 08 '22 05:11

riptidebyte