本文介绍了ui-router 解析在 Ionic 中表现得很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从演示 Ionic 应用程序开始(ionic start myApp sidemenu),并向其中一个视图添加了 resolve:

I started from a demo Ionic app (ionic start myApp sidemenu), and added a resolve to one of the views:

resolve: {
  issue: function($q, $timeout) {
    var defer = $q.defer();
    //defer.reject();       // Doesn't work browser or device
    $timeout(defer.reject); // Works in browser, but not device
    return defer.promise;
  }
}

我在这里监控被拒绝的resolve:

I monitor rejected resolves here:

.run(function($ionicPlatform, $rootScope, $ionicLoading) {
  $ionicPlatform.ready(function() {
    // regular stuff here

    $rootScope.$on('$stateChangeError', function() {
      $ionicLoading.show({
        template: 'All good!'
      });
    });
  });
});

由于某种原因,如果resolve立即拒绝(见上面的defer.reject()),$stateChangeError的回调不会运行.如果我做的完全一样,但在 Ionic 之外,它可以工作!

For some reason, if resolve rejects immediately (see defer.reject() above), the callback of $stateChangeError is not run. If I do exactly the same, but outside of Ionic, it works!

此外,尝试通过执行 $timeout(defer.reject); 来延迟 resolve 拒绝会导致不同的行为.现在它可以在浏览器中按预期工作,但仍然无法在设备上工作.尝试延迟更多,结果在设备上成功:

Moreover, trying to delay the resolve rejection by doing $timeout(defer.reject); results in a different behaviour. Now it works in a browser as expected, but still doesn't work on a device. Trying to delay even more, results in success on device:

$timeout(function() {
  defer.reject();
}, 250); // Doesn't work for me with 200 or less

有人能解释一下吗?

推荐答案

根据我在 Angular 和 promise 模型方面的经验.为了解决/拒绝一个承诺,Angular 必须在 JS 事件循环的一个循环中打勾 - nextTick - 这可以使用 $scope.apply() 来完成,这就是我们在单元测试中模拟这些事情的方式.

From my experience with Angular and the promise model. In order to resolve/reject a promise Angular must tick over one cycle of the JS event loop - nextTick - and this can be accomplished using $scope.apply() which is how we mock such things in unit tests.

这是一篇很棒的文章 谈到 $timeout 和 $scope.$evalAsync - 据我所知,$timeout 正在评估下一个滴答中的函数.这就是此代码按照您概述的方式工作的原因.

This is an awesome article that talks about $timeout and $scope.$evalAsync - from what I can gather $timeout is evaluating the function in the next tick. Which is the reason that this code works the way you outlined.

resolve: {
  issue: function($q, $timeout) {
    var defer = $q.defer();
    //defer.reject();       // <---- no nextTick
    $timeout(defer.reject); // <---- $timeout evaluates on nextTick
    return defer.promise;
  }
}

这是另一篇文章,讨论$q 的 textTick 实现.

This is another article that talks about the textTick implementation of $q.

我知道这不能解决您的问题 - 但它应该可以说明为什么会发生这种情况!祝你好运!

I know that this doesnt solve your problem - but it should shed some light onto why this is happening! Good luck!

这篇关于ui-router 解析在 Ionic 中表现得很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 12:14