【问题标题】:Issue with Ionic/Angular $watch fired before promise function filling data from pouchdb在从 pouchdb 填充数据的 Promise 函数之前触发 Ionic/Angular $watch 的问题
【发布时间】:2016-07-07 09:12:48
【问题描述】:

我真的不知道从哪里开始描述这个问题。 在互联网上查找一些信息非常困难。

我有这个 Ionic 应用程序(它使用 AngularJS)将数据保存到 PouchDB 本地数据库。

在主页中,我有一个嵌套视图,其中左侧列(第一个控制器)包含先前保存的数据列表,中间列(第二个控制器)包含用户从中选择的项目的详细信息离开了。

这是问题所在:当用户单击左列中的一项时,页面中心会启动一个新控制器,该控制器应显示详细信息,但显示空输入。 再次点击同一个项目,所有输入都被填满。

我在加载的变量中添加了一个 $watch,记录了值,我也在回调函数中这样做了。 当用户第一次点击时,结果如下:

($watch) myvar has changed from undefined to undefined
(setValues) myvar.name: test

当我再次点击时会发生这种情况:

($watch) myvar has changed from undefined to _id: 8ee32942-1c61-865b-2cd0-8d5b3d4a3082; name: test

加载左侧的项目也会出现同样的问题。

我从本地 PouchDB 加载数据。我没有实际查询数据库,而是尝试将其替换为

return Promise.resolve({'_id': 'test001', 'name': 'test'});

猜猜看……它起作用了!

所以现在的问题是:问题出在哪里?是控制器吗?是pouchdb吗?是离子框架吗?是加载功能吗?

最后是一些代码:

$scope.$watch('myvar', function( newValue, oldValue ) {
  console.log('($watch) myvar has changed from ' + printMyvar(oldValue) + ' to ' + printMyvar(newValue));
});

var printMyvar = function (var_to_print) {
  var s = 'undefined';
  if (var_to_print) {
    s = '_id: ' + var_to_print._id;
    s += '; name: ' + var_to_print.name;
  }
  return s;
}

var setValues = function (doc) {
  console.log('(setValues) name: ' + doc._id);
  $scope.myvar = doc;
};

$scope.isNew = ($stateParams.extId === 'new');

if ($scope.isNew) {
  $scope.myvar = { '_id': '', 'name': '' };
}  
else {
  Database.get( $stateParams.extId )
    .then( setValues )
    .catch( $scope.logError );
}

【问题讨论】:

    标签: javascript angularjs ionic-framework promise pouchdb


    【解决方案1】:

    请阅读为什么部分

    https://github.com/angular-pouchdb/angular-pouchdb

    PouchDB 是异步的,您通常需要调用 $scope.$apply() 才能将更改反映在 UI 上

    angular.controller('MyCtrl', function($scope, $window) {
      var db = $window.PouchDB('db');
      db.get('id')
        .then(function(res) {
          // Binding may/may not be updated depending on whether a digest cycle has
          // been triggered elsewhere as Angular is unaware that `get` has resolved.
          $scope.one = res;
        });
    
      var db2 = $window.PouchDB('db2');
      db.get('id')
        .then(function(res) {
          $scope.$apply(function() {
            // Value has been bound within Angular's context, so a digest will be
            // triggered and the DOM updated
            $scope.two = res;
          });
        });
    });
    

    【讨论】:

    • 谢谢毛罗!你救了我的命!添加 $scope.$apply 使整个工作正常。
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2014-11-15
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    相关资源
    最近更新 更多