【问题标题】:pass data from PouchDB Service to Controller in AngluarJS将数据从 CouchDB 服务传递到 AngularJS 中的控制器
【发布时间】:2016-05-01 16:31:31
【问题描述】:

我在 Angular/Ionic 中设置了一个 PouchDb 服务,该服务在服务中运行良好,但是当我尝试将从 PouchDB 服务检索到的数据传递给我的控制器时失败。

这是我的服务

angular.module('myApp', [])
.service('DBService', function($q) {
  var items;
  var db;
  var self = this;
  this.initDB = function() {
    return db = new PouchDB('simpleDB', {
      adapter: 'websql'
    });
  };
this.storeData = function() {
    return $q.when(
              db.put({
          _id: 'mydoc',
          title: 'some text'
        }).then(function (response) {
          // handle response
          console.log('done')
        }).catch(function (err) {
          console.log(err); 
        })
      )
  };
this.getData = function(){
  return $q.when(
    db.get('mydoc').then(function (doc) {
    // handle doc
    console.log(doc); // I see the data in console
     }).catch(function (err) {
     console.log(err);
     })
  )
}
})

这是控制器

angular.module('myApp', [])
.controller('mainCtrl', function($scope, DBService, $q) {
  $scope.getData = function(){
      DBService.initDB()
      DBService.getData().then(function(data){ 
        console.log(data)
      })
    }

当我使用 then() 时出现错误 TypeError: Cannot read property 'then' of undefined.

谁能帮我弄清楚如何正确地将数据从我的服务传递到控制器?

【问题讨论】:

    标签: angularjs angular-promise pouchdb


    【解决方案1】:

    我很幸运能很快找到错误!我没有在我的服务中返回数据,所以我将其更改为

    this.getData = function(){
      return $q.when(
        db.get('mydoc').then(function (doc) {
        // handle doc
        return doc; // I added this 
        console.log(doc); // I see the data in console
         }).catch(function (err) {
         console.log(err);
         })
      )
    }
    

    then() 返回 undefined 的原因是我不小心从 this.getData 函数的第二行省略了 return $q.when(!现在我在控制器中拥有了我需要的数据!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 2021-10-24
      • 2019-01-12
      • 2014-06-08
      相关资源
      最近更新 更多