我正在尝试编写一个函数来打开一个 angular-ui 模式窗口,并在它关闭后返回一个 promise 。这通常很容易,您只需返回模态实例,但在这种情况下,即使窗口关闭属性我也想检查 .then() 函数内的响应并可能拒绝基于状态代码的 promise ,即使它已经成功了。
这可能没有多大意义,所以这里有一些代码......
// Function which should return a promise
var myFunc = function(){
var modalInstance = $modal.open({
templateUrl: 'xxx',
controller: 'yyy',
});
return modalInstance.result.then(function (result) {
// If the login was successful then resolve
if(result && result.success === true){
// What goes here?
}
// If it was uncuccessful then reject, even though it was closed successfully.
else{
// What goes here?
}
}, function () {
$log.info('Modal was closed unsuccessfully');
});
}
myFunc.then(function(){
// DO something
});
最佳答案
您可以返回一个新的 promise ,只有当来自 $modalInstance.result 的 promise 得到解决并且您的状态代码检查正常时,该 promise 才会得到解决。类似的东西:
var myFunc = function(){
var modalInstance = $modal.open({
templateUrl: 'xxx',
controller: 'yyy',
});
var deferred = $q.defer();
modalInstance.result.then(function() {
if (/* status code checks ok */) {
deferred.resolve();
}
else {
deferred.reject();
}
}, function() {
deferred.reject();
});
return deferred.promise;
}
参见 docs on $q .
关于javascript - Angular - 返回 $modal promise 并拒绝它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33402663/