【问题标题】:Angular .then undefinedAngular .then 未定义
【发布时间】:2016-08-13 19:01:58
【问题描述】:

我正在尝试在 Angularjs 应用程序中实现 this promise pattern。但是 someUserContent 返回值 true 而不是所需的实际数据。如何将数据发送到控制器?

在我的控制器中:

.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);
    }
   }    
} 

【问题讨论】:

    标签: javascript angularjs promise angular-promise


    【解决方案1】:

    尝试传递引用而不是调用方法。您正在进行异步调用,它需要等待 promise 返回,当您在 then 方法中执行它们时,它们没有 promise,这就是您收到错误的原因。

     .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);
        }
       }    
    } 
    

    【讨论】:

    • 如果我这样做,.then(Myfactory.getUserContent) 会生成错误 Cannot read property 'allDocs' of null
    • self.db在getUserContent中不存在,尽量让你的db在全厂可用 this.db = new PouchDB('users', {location: 'default'});
    • var self = this; 不解决这个问题吗?更改为 this.db 未能解决错误。
    • 您在 checkUset 上下文中声明了这一点,并且它仅在此处可用,我更新了我的答案尝试一下。
    • 谢谢我试过你的答案,allDocs 仍然为空
    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 2014-11-29
    • 2015-09-13
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多