AngularJS Services – Fetching Server Data

Fetching Server Data – Intro

$http in AngularJS is the service that assists us with fetching data from remote http services.
The simple way for using it is when you need data in a controller, then issue the $http call and use the data. This way works 100%, but as always our application is getting bigger…
If you do not manage your services you’ll find yourself writing the same http call dozens of times. If you want to avoid this (and you do!), then you can use AngularJS Services.

There are several ways for solving this problem via AngularJS Services. In this post, I’ll describe 2 ways for solving the reuse of $http.
1. One service endpoint for managing the entire http calls in our application.
2. One service for every model you have in your application.
This mean that you have several services.

AngularJS logo

AngularJS

Simple Usage Example

Lets say you have e-commerce store, and you have 3 models – products, categories and users.
Now probably, you want to make CRUD operations on every type of models you have in your e-commerce store.

I’ll give 2 “How To’s”, for solving this issue using AngularJS Services.

One Service Endpoint

angular.module('angular-shop-http').service('httpService', function($rootScope, $http, $q) {
    var httpService = {};

    httpService.get = function(id, endpoint) {
        var deferred = $q.defer();
        var url = 'www.panda-os.com/' + endPoint;
        var queryParams = {};
        if (typeof id != 'undefined' && typeof id != null) {
            queryParams = { id: id};
        }
        $http({
            method: 'GET',
            url: url,
            headers: {
                'Content-Type': 'application/json',
            },
            params: queryParams,
            cache: false
        }).
            success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).
            error(function(data, status, headers, config) {
                deferred.reject(data);
            });

        return deferred.promise;
    };

    return httpService;

});

Code Review

As you can see, we created one endpoint service for issuing all http calls.
Now all we have to do is call the “httpService.get()” function with the requested endpoint (products, user, categories) and the relevant params.
NOTE: I only show the get function, we should also implement the rest of the CRUD operations.

One Service For Every Model

-Product Service

angular.module('angular-shop-products').service('productService', function($rootScope, $http, $q) {
    var productService = {};

    productService.get = function(id) {
        var deferred = $q.defer();
        var endPoint = "products/";
        var url = 'www.panda-os.com/' + endPoint;
        var queryParams = {};
        if (typeof id != 'undefined' && typeof id != null) {
            queryParams = { id: id};
        }
        $http({
            method: 'GET',
            url: url,
            headers: {
                'Content-Type': 'application/json',

            },
            params: queryParams,
            cache: false
        }).
            success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).
            error(function(data, status, headers, config) {
                deferred.reject(data);
            });

        return deferred.promise;
    };

    return productService;

});

-User Service

angular.module('angular-shop-products').service('userService', function($rootScope, $http, $q) {
    var userService = {};

    userService.get = function(id) {
        var deferred = $q.defer();
        var endPoint = "user/";
        var url = 'www.panda-os.com/' + endPoint;
        var queryParams = {};
        if (typeof id != 'undefined' && typeof id != null) {
            queryParams = { id: id};
        }
        $http({
            method: 'GET',
            url: url,
            headers: {
                'Content-Type': 'application/json',

            },
            params: queryParams,
            cache: false
        }).
            success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).
            error(function(data, status, headers, config) {
                deferred.reject(data);
            });

        return deferred.promise;
    };

    return userService;

});

Code Review

In the above code sample you can see that there is one endpoint service for every model.
Every service is responsible for the model operations. You can add operations to every model by adding more functions to the model service.

Read more about our AngularJS Services posts series

AngularJS Service
AngularJS Service – Application Data Management
AngularJS Service – Application Business Logic

2 thoughts on “AngularJS Services – Fetching Server Data

  1. Pingback: AngularJS Services - Application Business Logic | The Panda Blog

  2. Pingback: AngularJS Services - Application Data Management | The Panda Blog

Leave a Reply

Your email address will not be published. Required fields are marked *