Reputation: 987
I'm struggling working with $cacheFactory, i'm trying to cache a simple GET request and then retrieve it from the controller - but i don't understand how can i do it.
Here is the Service
app.service('usersService', function ($http, $cacheFactory, $q) {
var cache = $cacheFactory("todoList");
this.getToDos = function() {
var deferred = $q.defer();
var req = {
method: 'GET',
url:'https://jsonplaceholder.typicode.com/todos',
cache: true
};
var data = cache.get("todoList");
if (!data) {
$http(req).then(function(payload) {
deferred.resolve(payload.data);
cache.put("todoList", payload.data);
}, function(reason) {
deferred.reject(reason);
});
} else {
return data;
}
return deferred.promise;
};
})
And here is the controller
app.controller('usersListController', function ($scope, usersService, BookService, $cacheFactory) {
function init() {
$scope.refresh();
usersService.getToDos();
var sharedCache = $cacheFactory.get('todoList'); // getting undefined
console.log(sharedCache);
}
init();
});
I guess the problem is that the GET request is asynchronous - so by the time the controller executes the init function - the GET doesn't "get" anything .....
Upvotes: 0
Views: 35
Reputation: 4448
Your guess is correct, since request is asynchronous by the time
var sharedCache = $cacheFactory.get('todoList');
is running, your todoList may or may not be set. What you can do is to return a promise from your service.
this.getToDos = function() {
var req = {
method: 'GET',
url:'https://jsonplaceholder.typicode.com/todos',
cache: true
};
return req;
};
and resolve your promise inside your controller.
var promise = usersService.getToDos();
promise.then(function (recieved) {
},
function (error) {
});
Upvotes: 0
Reputation: 11
Try to replace this one
var sharedCache = $cacheFactory.get('todoList');
to
var cache = $cacheFactory('todoList'); cache.get();
Note- Refer this link https://docs.angularjs.org/api/ng/service/$cacheFactory
Syntax - $cacheFactory(Key); //get data
Upvotes: 0