When trying to get the information stored in localstorage through a factory by injecting it into the controller, the following error occurs.
TypeError: getGroupsProf.dataGroups(...).then is not a function
The code is the following:
angular.module('gruposProfesor', ['ionic', 'ngCordova'])
.controller('mostrarGruposProf', mostrarGruposProf)
.factory('obtenerGruposProf', obtenerGruposProf);
mostrarGruposProf.$inject = ['$scope', 'obtenerGruposProf'];
function mostrarGruposProf($scope, obtenerGruposProf) {
obtenerGruposProf.datosGrupos().then(function(data) {
console.log(data);
});
}
function obtenerGruposProf() {
return {
datosGrupos: function() {
var getGrupos, infoGrupos;
getGrupos = localStorage.getItem('GruposProf');
infoGrupos = JSON.parse(getGrupos);
return infoGrupos;
}
};
}
Thanks in advance for any assistance.
If you're using a method
.then
, the object that precedes it is most likely a thenable (or an object that has a then method ). Usually who implements this type of method are the Promises . Looking at your code more closely we havewhom you then call
The error occurs because the function
datosGrupos
does not return a promise and therefore there is no method.then
. What that function returns as such is the data that you have in the localStorage, an ordinary object.To get a promise back you should do something like
You'd basically be returning a promise with the future result already resolved. This is an error for two reasons
You are creating asynchrony in an operation that is unavoidably synchronous.
Operations on localStorage are synchronous. The getItem method immediately returns a string, which is the result of the operation, not a future result.
It is much simpler to write
what to write
since you are creating unnecessary nesting. This puts you one step closer to the callback-hell which is one of the reasons promises exist.
Usually writing promises that way is considered an anti -pattern since
As you saw before you don't need to create indentation and in case of error you can use a simple try...catch
There is a case in which it is convenient for you to write the code in this way and that is when, for example, you have to make an ajax call or return a stored result. Basically you have two options, one is synchronous and the other is asynchronous. In this case you can do this.
Then you manipulate your data using
In this case deferred if necessary since you can't know for sure if the call will be asynchronous or not and the use of
.then
is fully justified.Finally keep in mind that if you want to cache the result of your ajax calls in localStorage there is already a service to do that.
Take a look at https://github.com/jmdobry/angular-cache .