1

I'm using Sails.js as base for my project, and so far I'm trying to modularize every UI element using AngularJS.

Although I think this approach is good because it allows me to reuse my code as much as possible, in the end I will have to make many HTTP requests to the server because each module doesn't share data with the others.

So, what would be a solution to mitigate the number of requests and share the data among all controllers?

I have thought of 2 different solutions:

  • Populate views from the back-end reducing the amount of data the AngularJS controllers are requesting.
  • Request data dynamically using sockets and cache the commonly used queries.
siannone
  • 6,617
  • 15
  • 59
  • 89

3 Answers3

1

I have found out that you can cache HTTP requests in AngularJS using $cacheFactory (documentation here).

An easy way to do it is the following one:

$http({
    url : '/your/path',
    method : 'POST',
    cache : true
})
.success(function (data) {
    data;
})

More informations can be found on coderwall and on this StackOverflow question.

Community
  • 1
  • 1
siannone
  • 6,617
  • 15
  • 59
  • 89
1

An angular service is typically used to share data between controllers. Here's a simple example of what that may look like. Note it will only make a request to get data the first time, after that it will use the stored value.

app.factory('dataService', function () {
    var service = {};
    var data;

    service.getData = function () {
        if (!data) {
            //populate data via http get or whatever
        }
        return data;
    }

    return service;
});

This service can then be injected into any controller.

aw04
  • 10,857
  • 10
  • 56
  • 89
0

Have you taken a look at angular-cache and angular-data? It's both a wrapper to the built in angular data communication layer, as well as a client side data store.

Evanion
  • 188
  • 3
  • 12