eugenekgn
eugenekgn

Reputation: 1722

Angular $http get with :id

I am trying to get the following to url path using angular $http service.

let's say I have a string

'/api/users/:id/fullinfo'

, and an id of 5, how do I get this string have following format:

'/api/users/5/fullinfo'

, via $http.get() method or $resource api.

Upvotes: 2

Views: 9271

Answers (3)

Alfonso Presa
Alfonso Presa

Reputation: 1034

Code

Include this service in your app:

    app.service(
        "httpi",
        function( $http ) {
            return( httpProxy );
            // I proxy the $http service and merge the params and data values into
            // the URL before creating the underlying request.
            function httpProxy( config ) {
                config.url = interpolateUrl( config.url, config.params, config.data );
                return( $http( config ) );
            }
            // I move values from the params and data arguments into the URL where
            // there is a match for labels. When the match occurs, the key-value
            // pairs are removed from the parent object and merged into the string
            // value of the URL.
            function interpolateUrl( url, params, data ) {
                // Make sure we have an object to work with - makes the rest of the
                // logic easier.
                params = ( params || {} );
                data = ( data || {} );
                // Strip out the delimiter fluff that is only there for readability
                // of the optional label paths.
                url = url.replace( /(\(\s*|\s*\)|\s*\|\s*)/g, "" );
                // Replace each label in the URL (ex, :userID).
                url = url.replace(
                    /:([a-z]\w*)/gi,
                    function( $0, label ) {
                        // NOTE: Giving "data" precedence over "params".
                        return( popFirstKey( data, params, label ) || "" );
                    }
                );
                // Strip out any repeating slashes (but NOT the http:// version).
                url = url.replace( /(^|[^:])[\/]{2,}/g, "$1/" );
                // Strip out any trailing slash.
                url = url.replace( /\/+$/i, "" );
                return( url );
            }
            // I take 1..N objects and a key and perform a popKey() action on the
            // first object that contains the given key. If other objects in the list
            // also have the key, they are ignored.
            function popFirstKey( object1, object2, objectN, key ) {
                // Convert the arguments list into a true array so we can easily
                // pluck values from either end.
                var objects = Array.prototype.slice.call( arguments );
                // The key will always be the last item in the argument collection.
                var key = objects.pop();
                var object = null;
                // Iterate over the arguments, looking for the first object that
                // contains a reference to the given key.
                while ( object = objects.shift() ) {
                    if ( object.hasOwnProperty( key ) ) {
                        return( popKey( object, key ) );
                    }
                }
            }
            // I delete the key from the given object and return the value.
            function popKey( object, key ) {
                var value = object[ key ];
                delete( object[ key ] );
                return( value );
            }
        }
    );

Usage

After including, and injecting it you should be able to perform the following

httpi({
    method: "post",
    url: "/sample/:id",
    data: {
        id: "1"
    }
});

And it will call to "/sample/1" with POST and no more data.

Source: http://www.bennadel.com/blog/2613-using-url-interpolation-with-http-in-angularjs.htm Running sample: http://plnkr.co/edit/xnPpzweXZFQvSccA5xFK?p=preview

Upvotes: 0

Andy Poquette
Andy Poquette

Reputation: 410

You should be able to use $interpolate

var getPath = '/api/users/{{id}}/fullinfo';
$scope.id= '5';
$interpolate(getPath)($scope);

Alternatively you can also do:

var path = '/api/users/' + id + '/fullinfo';

But the interpolate is better.

https://docs.angularjs.org/api/ng/service/$interpolate

Upvotes: 1

GPicazo
GPicazo

Reputation: 6676

I think what you are saying is that you have a GET API endpoint in your application that responds to the dynamic route '/api/users/:id/fullinfo', and you are trying to figure out how to make the GET request using the $http provider right? If that is the case, then you can do something like the following:

// create a service to manage the users resource
app.factory('UsersService', ['$http', function($http) {
    function getById(id) {
        var requestUrl = '/api/users/' + id + '/fullinfo';
        return $http.get(requestUrl).then(function(resp) {
            return resp.data;
        }, function(err) {
            // handle request error generically
        });
    }

    return {
        getById: getById
    };
}]);

// consume the service in a controller like so:
app.controller('YourController', ['$scope', 'UsersService', function($scope, UsersService) {
    var userId = 5; // you might also get this value from state params or some other dynamic way

    UsersService.getById(userId).then(function(userInfo) {
        $scope.userInfo = userInfo;
    });
}]);

Upvotes: 1

Related Questions