AngularJS - Send $http GET request with associativ

2019-07-16 05:12发布

问题:

with this code I am trying to send a $http.get request to my rest service:

$http({
    method: 'GET',
    url: '/api/item/all',
    params: {
        query: {
            userid: 7
        },
        fields: 'title'
    }
});

I expected to access this URL:

/api/item/all?query[userid]=7&fields=title

but I am always getting a malformed url...

So, how to proceed?

Or even better: Is it possible to pass the full request url into the url-param of $http?

回答1:

In a GET request, you should pass parameters as part of the query string.

You can use the shortcut get call and pass in the query parameters in the url:

$http.get('api/item/all?userid=" + 7 + "&fields=title");

If you need to access them as scope variables, you can do that too:

$http.get('api/item/all?userid=" + $scope.foo + "&fields=" + $scope.bar);

Also depending on the back end you can send them as a path parameters rather then a query parameter:

$http.get('api/item/all/userid/" + $scope.foo + "/fields/" + $scope.bar);

Hope that helps