Friday, 17 June 2016

AngularJS Create common factory to make get / posts requests to the web api.

For make the get/post requests in angularjs I have created following factory. This factory has two methods for handle get and post requests. 

angular.module('requestUtils', []).factory("RequestUtils", ["$http", "$state", function ($http, $state) {
    return {
        MakeGetCall: function (url, params, callback, errorCallback) {
            $http.get(url, {
                params: params
            }).success(function (data) {
                callback(data);
            }).error(function (data) {
                errorCallback(data);
            });
        },

        MakePostOrPutCall: function (url, method, params, callback, errorCallback) {
            $http({
                headers: { 'Content-Type': 'application/json' },
                url: url,
                method: method,
                data: params,
            }).success(function (response) {
                callback(response)
            }).error(function (response) {
                //if (response.Error.ErrorCode == 401) {
                //    $state.go("app.login");
                //}
                //else {
                errorCallback(response);
                //}
            });
        },

        ServerPath: function () {
            return "http://www.someapi.com/api";
        }
    }
}]);


Usage:

For consume this factory in the app you just need to add "requestUtils" in the app.js file as following:

var myApp = angular.module("myApp", ["ngRoute", "ngStorage", 'requestUtils',"ngDialog"]);


Now inject that requestUtils factory in your angular controller where you want to consume its methods. 

myApp.controller("itemCtrl", ["$scope", "$state", "RequestUtils", function ($scope, $state, RequestUtils) {
$scope.vm = this;

$scope.vm.makePost = function () {
        var url = RequestUtils.ServerPath() + "/Item/Post");
        RequestUtils.MakePostOrPutCall(url, 'POST', {id:1, name:'test'}, function (response) {
            console.log(response);
        }, function (errorResponse) {
            console.log(errorResponse);
        });
    };

$scope.vm.getData = function () {
        RequestUtils.MakeGetCall(RequestUtils.ServerPath() + '/Item/GetItem', {}, function (response) {
          console.log(response);
        },
        function (errorResponse) {
            console.log(errorResponse);
        });
    }
}]);

No comments:

Post a Comment