5

我发现当你双向绑定一个promise时,angular会为你解析promise并绑定实际的promise。那么我的问题是,如何处理被拒绝的承诺?

我的特殊情况是我有一个指令,我在其中双向绑定来自控制器的承诺。我的控制器希望该指令能够处理拒绝该承诺,因为错误需要显示在 DOM 上。

在我的指令中,我希望我的绑定变量是一个承诺,但相反,我得到了该承诺的已解决值。烦人,但并不可怕。

问题是当该承诺被拒绝时,指令无法知道

以这个 plunker 为例:

http://plnkr.co/edit/m0cOqFhx6TNrDxTbr9Qx?p=preview

如何处理指令中的承诺拒绝?

谢谢,罗伊

4

2 回答 2

1

我有三个建议 - 没有一个是完美的,但它们都有效:

  1. 创建一个返回 promise 的 getter 方法并将此方法绑定到指令使用&

  2. 绑定延迟对象而不是promise(丑陋)

  3. 当承诺解决/被拒绝时广播一个事件

我创建了一个包含所有建议的 plunker:http ://plnkr.co/edit/jsA0PwpQm0xycLclkBU3?p=preview

  • 控制器:
app.controller('MainCtrl', function($scope,$q,$timeout) {
  var deferred = $q.defer();

  $scope.promise = deferred.promise;
  $scope.deferred = deferred;

  $scope.getPromise = function(){
    return deferred.promise;
  }

  $scope.promise.then(function(msg){
    $scope.$broadcast('promiseThen',{rejected:false,msg:msg});
  },function(msg){
    $scope.$broadcast('promiseThen',{rejected:true,msg:msg});
  });

  $timeout(function(){deferred.reject('No reason...');},1500)
});
  • 标记:
<div promise-test deferred="deferred" get-promise='getPromise()' ></div>
  • 指示:
app.directive('promiseTest',function(){
  return {
    template:'<div>m1: {{m1}}<br>m2: {{m2}}<br>m3: {{m3}}</div>',
    scope:{getPromise:'&',deferred:'='}
    ,link:function(scope,el,attrs){

      scope.m1 = scope.m2 = scope.m3 = 'Waiting...';

      scope.getPromise().then(function(msg){
        scope.m1 = 'Resolve getPromise: '+msg;
      },function(msg){
        scope.m1 = 'Reject getPromise: '+msg;
      })

      scope.deferred.promise.then(function(msg){
        scope.m2 = 'Resolved deferred.promise: '+msg
      },function(msg){
        scope.m2 = 'Rejected deferred.promise: '+msg
      });

      scope.$on('promiseThen',function(ev,val){
        if(val.rejected){
          scope.m3 = 'Rejected promiseThen: '+val.msg
        }else{
          scope.m3 = 'Resolved promiseThen: '+val.msg          
        }
      })
    }
  }
})
于 2013-04-27T20:28:35.710 回答
1

成功和错误回调可以使用&.

在此选项中,控制器负责将回调添加到.then.

控制器

app.controller('MainCtrl', function($scope,$q,$timeout) {
  var deferred = $q.defer();

  $scope.register = function(callback, errback) {
    deferred.promise.then(callback, errback);
  }

  $timeout(function(){deferred.reject('No reason...');},1500)
});

指示

app.directive('promiseTest',function(){
  return {
    template:'<div>m1: {{m1}}',
    scope:{register:'&'},
    link:function(scope,el,attrs){

      scope.m1 = 'Waiting...';

      scope.register({
        success: function(msg){
          scope.m1 = 'Resolve getPromise: '+msg;
        },
        errback: function(msg){
          scope.m1 = 'Reject getPromise: '+msg;
        }
      });
    }
  }
})

HTML

<div promise-test register='register(success, errback)' ></div>

plunkr

于 2013-09-04T00:52:37.693 回答