首页 文章

AngularJS:service的布尔方法是否应该返回为true / false或者被解析/拒绝的promise?

提问于
浏览
7

承诺使用的模式仍然让我困惑 .

例如,在Angular应用程序中,我有一个带有方法 emailExists(email) 的服务 usersService . 显然,它会向服务器执行请求,以检查给定的电子邮件是否已存在 .

我很自然地让方法 emailExists(email) 返回在正常操作中解析为 truefalse 的承诺 . 如果我们只有一些意外错误(例如,服务器返回 500: internal server error ,则应拒绝承诺,但在正常操作中,它将被解析为相应的布尔值 .

Hovewer,当我开始实现我的异步验证器指令(通过 $asyncValidators )时,我发现它想要解析/拒绝承诺 . 所以,到现在为止,我最终得到了这个相当丑陋的代码:

'use strict';

(function(){

   angular.module('users')
   .directive('emailExistsValidator', emailExistsValidator);


   emailExistsValidator.$inject = [ '$q', 'usersService' ];
   function emailExistsValidator($q, usersService){
      return {
         require: 'ngModel',
         link : function(scope, element, attrs, ngModel) {

            ngModel.$asyncValidators.emailExists = function(modelValue, viewValue){
               return usersService.emailExists(viewValue)
               .then(
                  function(email_exists) {
                     // instead of just returning !email_exists,
                     // we have to perform conversion from true/false
                     // to resolved/rejected promise
                     if (!email_exists){
                        //-- email does not exist, so, return resolved promise
                        return $q.when();
                     } else {
                        //-- email already exists, so, return rejected promise
                        return $q.reject();
                     }
                  }
               );
            };
         }
      }
   };

})();

它让我觉得我应该修改我的服务,以便它返回已解决/拒绝的承诺 . 但是,对我来说这感觉有点不自然:在我看来,被拒绝的承诺意味着“ we can't get result ", not " negative result ” .

或者,我是否误解了承诺的用法?

或者,我应该提供两种方法吗?命名它们的常见模式是什么?

任何帮助表示赞赏 .

1 回答

  • 2

    在这种情况下,没有正确/不正确的方法来解决这个问题 . 您对电子邮件检查服务的评价听起来很合理:实际上,数据库中电子邮件的存在并不严格表示失败情况,承诺拒绝通常对应并反映 .

    另一方面,如果你考虑一下,Angular实现异步验证器的方式也是有意义的 . 失败的验证结果在概念上感觉像是失败,不是在HTTP方面,而是在业务逻辑意义上 .

    所以在这种情况下,我可能会调整我的自定义服务,至少返回非成功状态,如409 Conflict .

    如果您仍想返回200个成功代码以及真/假共振,您仍然可以使验证器代码稍微不那么难看:

    ngModel.$asyncValidators.emailExists = function (modelValue, viewValue) {
        return usersService.emailExists(viewValue).then(function (email_exists) {
            return $q[email_exists ? 'when' : 'reject']();
        });
    };
    

相关问题