gpt4 book ai didi

javascript - asyncvalidator promise 未得到解决

转载 作者:行者123 更新时间:2023-11-28 18:32:27 24 4
gpt4 key购买 nike

我正在尝试取消 $asyncValidator promise ,但抛出了未定义的错误,这是我的代码:

(function () {
'use strict';

angular
.module("webclient.common.directives")
.directive("duplicateModelNameValidator",
["$q",
"modelManager",
duplicateModelNameValidator
]);

function duplicateModelNameValidator($q, modelManager) {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
var classId = attrs.duplicateModelNameValidator;

ngModel.$asyncValidators.duplicateModelName = function (modelValue) {
var defer = $q.defer();
//if the user hasn't touched the input box I don't want to call the database code
if (ngModel.$pristine)
//I want to resolve the promise but get the error below?
return defer.resolve();

modelManager.find(modelValue, false).then(function (data) {
if (data.exists === true)
// Found a row
return defer.reject();
else
// Did not find a row
return defer.resolve();
});

return defer.promise;
}
}
}
}
}());

代码抛出错误:

[ngModel:nopromise] 预期异步验证器返回一个 Promise,但结果却是“未定义”。

谢谢

最佳答案

方法defer.resolve()defer.reject()控制defer.promise的状态,它们>不返回 promise ,而验证器函数预计返回 promise 。您应该改用 $q.when()$q.reject() 方法:

ngModel.$asyncValidators.duplicateModelName = function (modelValue) {
//if the user hasn't touched the input box I don't want to call the database code
if (ngModel.$pristine) {
return $q.when(true);
}

return modelManager.find(modelValue, false)
.then(function (data) {
if (data.exists === true) {
// Found a row
// this will reject the promise returned by modelManager.find()
return $q.reject('exists');
}

// Did not find a row
// no need to do anything, this promise is already
// resolved which will succeed the validation
});
}

关于javascript - asyncvalidator promise 未得到解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com