ottz0 ottz0 - 6 months ago 14
AngularJS Question

Accessing Returned data from Controller

I have data in a factory that I can view in the console.log from in the function, how can I get it into my controller?

It just comes back as undefined.

Factory

.factory('ThemeColor', function() {
var db = new PouchDB('myDB');
var self = {
getColor: function(){
db.get('themeColor').then(function(data){
console.log(data);
return data;
});
},
}

return self;
});


Controller

$scope.ThemeColor = function(){
ThemeColor.getColor().then(function(data){
console.log(data);
});
};

Answer

PouchDB returns a Promise. Angular needs to know about the Promise when it resolves. As such, In your controller, use inject $q service and wrap the factory in `$q.when() as follows:

.factory('ThemeColor', function($q) {
var db = new PouchDB('myDB');
var self = {
  getColor: function(){
  return $q.when(db.get('themeColor')).then(function (data) {          
      return data;
    }).catch(function(err){
      console.error(err);
   });
  }
}

return self;
});

You can check out the docs

  1. Angular documentation on $q.when()

  2. PouchDB note on Angular's $q.when() . Read the Section Promises

Comments