Astaroth
Astaroth

Reputation: 783

How to use ngResource-like query urls with $http

I'm using Angular and I've got to do some not-restful ajax calls. And, because of that I can't use ngResource. My URL are something like /admin/:someId or /admin/:someId/users/:someUserId.

The ngResource methods just parse those tokens but, is there some way to use those URLs with the $http object?

I'm exposing my backend routes to javascript in the following manner: /slug/:param1/slug/:param2. With the ngResource methods I have to do the following to get it working: Resource.query({param1: someValue, param2: anotherValue});. The problem is that I cannot use ngResource in this case and I am not able to get it working with the $http.get method, it does not replace the tokens :param1 and :param2 for the values. It just calls to /slug/:param1/slug/:param2.

Upvotes: 2

Views: 160

Answers (1)

Astaroth
Astaroth

Reputation: 783

Just in case someone finds this thread, I ended doing this:

.factory('RouteUtils', function () {
return {
    /**
     * Replaces all token appearances with their corresponding value.
     * 
     * @param string route The route that has the tokens you want to replace. Tokens must be like ":someString".
     * @param object params Object of parameters. It must be key value. For example: {firstKey: 34, secondKey: 'I'm some string'}.
     * 
     * @returns string Token replaced route.
     */
    parse: function (route, params) {
        var propNames = Object.getOwnPropertyNames(params);
        propNames.forEach(function (propName) {
            route = route.replace(':' + propName, encodeURI(params[propName]))
        });

        return route;
    }
};

})

Then on the $http call:

.factory('SomeFactory', function ($http, RouteUtils) {
    return {
        someGetCall: function (params) {
            return $http.get(RouteUtils.parse(routeGet, params));
        },
        somePostCall: function (params) {
            return $http.post(RouteUtils.parse(routePost, params), {
                postParam1: 'postValue1',
                postParam2: 'postValue2'
            });
        },
    };
})

Being the variable route something like /user/:userId/games/:gameId/ and params something like {userId: 34, gameId: 55} the parse method would return /user/34/games/55/

It's the best solution I could think of since I wasn't able to find a native Angular way to do it.

Upvotes: 1

Related Questions