javascript - Cache $resource api request globally for controllers -
my angular application pretty relies on 1 api call (for example /api/example).
i have multiple routes, modules, , controllers need use data api request. example have:
public |__feature1 |__ feature1.controller.js |__ feature1.route.js |__feature2 |__ feature2.controller.js |__ feature2.route.js |__core |__ core.controller.js |__ core.nav.controller.js |__ core.route.js |__ core.service.js |__ app.js each of feature controllers need data /api/example.
an example of core.service.js
angular.module('myapp') .factory('mainservice', ['$resource' function($resource) { return $resource('/api/example', {}, { get: { method: 'get' } }); } ]); usually in feature1/feature.controller.js:
angular.module('feature1') .controller('feature1ctrl', ['mainservice', function(mainservice){ mainservice .get() .$promise .then(function(data){ console.log(data); }); } ]); and same thing in feature2/feature2.controller.js
angular.module('feature2') .controller('feature2ctrl', ['mainservice', function(mainservice){ mainservice .get() .$promise .then(function(data){ // same data again console.log(data); }); } ]); is there way application can call api , cache request data other controllers can access without having make multiple requests.
so maybe like:
angular.module('core') .controller('navctrl', ['mainservicedata', function(mainservicedata){ // don't make request, serve data console.log(mainservicedata); } ]);
if understand correctly, can cache without difficulty. add cache : true such
angular.module('myapp') .factory('mainservice', ['$resource' function($resource) { return $resource('/api/example', {}, { get: { method: 'get', cache : true // -- cached } }); } ]); i'd recommend taking @ $cachefactory if need more involved solution.
Comments
Post a Comment