2016-08-13 23 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