Click here to Skip to main content
15,883,938 members
Articles / Web Development / CSS3
Tip/Trick

AngularJS Data Sharing Controller to Controller to Service to API

Rate me:
Please Sign up or sign in to vote.
4.83/5 (4 votes)
3 Mar 2016CPOL1 min read 17.5K   6   3
Getting it all together - Controller, Service, $http, caching and more

Background

A common issue that people discuss is about data sharing, how should we get data from some server API to an angular controller and then share this data with other controllers.

Do Not Use $http Directly

Some people like to use $http in the controller to directly call their server side API.

JavaScript
function DisplayDataController($http) {
 $http.get(configuration.consts.baseApiUrl + 'ServerUrl/GetSomeValue', {id: id}).then(function (data) {

 });
}

This is bad practice for a few reasons:

  • The controller should handle display logic only.
  • If you want to change the call and reuse it in different places, you need to change it in all locations.
  • Each controller stores its own data and may potentially cost in multiple calls that can be minimized to one.

Using AngularJS Service

First, let's start to encapsulate under a single facade all of the outgoing API calls, for this, we will create an angularJS service. A service in angular is very useful especially considering the fact that it's actually a singleton, we will use this to our advantage later on.

JavaScript
MyModule.service('DataService', function ($http) {
   this.GetSomeData = function(id) {
      return $http.get(configuration.consts.baseApiUrl + 'ServerUrl/GetSomeData', {id: id});
   };
});

MyModule.controller('DisplayDataController', function (DataService) {
   DataService.GetSomeData(id).then(function (data) {
       // Use the data
   });
});

Note: Read the following article in order to understand how to skip using data.data (the http response object) and simply access the actual data from the server: http://www.codeproject.com/Articles/1078528/AngularJS-Loader-and-Error-Handling-Infrastructure

What we have done is create a service which calls $http. Now the controller uses the service and not directly the $http.

But if a different controller will use this service, it will call the server again, sure we can set cache: true, but this is a simple example, what will happen in a highly complex system?

Final Solution, Service With Caching Mechanism

Now let's add some caching logic for the complete solution:

JavaScript
MyModule.service('DataService', function ($http, $q) {
        var cache = {};
        return {
            get: function(id) {
                var deferred = $q.defer();

                if (cache[id] != null) {
                        deferred.resolve(cache[id]);
                    } else {
                        $http.get(configuration.consts.baseApiUrl + 
			'ServerUrl/GetSomeData', {id: id}).then(function(data) {
                            cache[id] = data.data[0];
                            deferred.resolve(data.data[0]);
                        });
                    }

                return deferred.promise;
            }
        };
    });

So what we've accomplished here is a service with a cache, now we can call our "DataService" from different controllers and share the same logic and data.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Payoneer
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionRe: AngularJS Data Sharing Controller to Controller to Service to API Pin
Konstantin A. Magg4-Mar-16 22:34
Konstantin A. Magg4-Mar-16 22:34 
AnswerRe: AngularJS Data Sharing Controller to Controller to Service to API Pin
dumsky5-Mar-16 20:13
dumsky5-Mar-16 20:13 
GeneralRe: AngularJS Data Sharing Controller to Controller to Service to API Pin
Konstantin A. Magg6-Mar-16 1:24
Konstantin A. Magg6-Mar-16 1:24 
So you reload your application after pushing data to the server? D'accord. Think this will be fine, if you have a rather "private" data set for each client on the server.

thx.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.