AngularJS: Custom Factory to call RESTful end points

Standard

Since I am a .net full stack developer, So have to used angularjs $http services a lot to utilize restful api’s in order to perform CRUD operations. So I come up with unified factory method which handles API requests with parameter and without parameter for GET/POST. Just have to pass request type, URL and parameter object to function and it will serve the need.

app.factory("webApi", [
    '$http', '$templateCache', function ($http, $templateCache) {
        return {
            withParameter: function (methodType, webApiUrl, parameterObject) {
                return $http({
                    method: methodType,
                    url: window.location.protocol + '//' + window.location.host + window.location.pathname + webApiUrl,
                    data: parameterObject,
                    cache: $templateCache
                });
            },
            nonParameter: function (methodType, webApiUrl) {
                return $http({
                    method: methodType,
                    url: window.location.protocol + '//' + window.location.host + window.location.pathname + webApiUrl,
                    cache: $templateCache
                });
            }
        }
    }
]);
Invoking code sample:
 angular.module('myServices', [])
        .factory("webService", [
            'webApi', function(webApi) {
                return {
                    getList: function () {
                        return webApi.nonParameter('GET', '/api/myController/getMyList');
                    },
                    addRecord: function (newObject) {
                        return webApi.withParameter('POST', '/api/myController/saveRecord', newObject);
                    }
                }
            }
        ]);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s