2016-08-13 41 views
-1

我想在Angularjs应用中实现this promise pattern。但someUserContent返回值不是所需的实际数据值true。如何将数据传送给控制器?Angular.then undefined

在我的控制器:

.controller('MyCtrl',function() { 

    MyFactory.checkUser(userId) //returns true 
    .then(MyFactory.prepDatabase()) //returns true 
    .then(Myfactory.getUserContent()) //returns a someUserData 
    .then(function(someUserData) { 
     //do some stuff with all this data 
    }); 
} 

,工厂:

.factory('MyFactory', function($q,$http....) { 

    MyFactory.prototype.checkUser = function(user_id) { 
     var self = this; 
     this.db = new PouchDB('users', {location: 'default'}); 
     return $q.when(true); 
    } 

    Myfactory.prototype.getUserContent = function() { 
    if (!self.someUserData) { 
     return $q.when(self.db.allDocs({ include_docs: true})) 
     .then(function(docs) { 
      self.someUserData = docs.rows.map(function(row) { 
      return row.doc; 
      }); 
      return $q.when(self.someUserData); 
     }) 
    } else { 
     return $q.when(self.someUserData); 
    } 
    }  
} 

回答

0

试图通过引用,而不是调用方法。你正在做异步调用,它需要等待承诺已经返回,当你在内部执行它们时,他们没有承诺,这就是为什么你会得到错误。

.then(MyFactory.prepDatabase) 
    .then(Myfactory.getUserContent) 

,改变你的工厂

.factory('MyFactory', function($q,$http....) { 
var db = new PouchDB('users', {location: 'default'}); 
    MyFactory.prototype.checkUser = function(user_id) { 
     var self = this;    
     return $q.when(true); 
    } 

    Myfactory.prototype.getUserContent = function() { 
    if (!self.someUserData) { 
     return $q.when(db.allDocs({ include_docs: true})) 
     .then(function(docs) { 
      self.someUserData = docs.rows.map(function(row) { 
      return row.doc; 
      }); 
      return $q.when(self.someUserData); 
     }) 
    } else { 
     return $q.when(self.someUserData); 
    } 
    }  
} 
+0

如果我这样做,'。然后(Myfactory.getUserContent)'产生 – lilbiscuit

+0

self.db不null'的错误'无法读取属性 'allDocs'存在于getUserContent中,尝试使整个工厂的youre db可用 this.db = new PouchDB('users',{location:'default'}); –

+0

不'var self = this;'照顾这个问题?更改为'this.db'不能解决该错误。 – lilbiscuit