Angular-返回$modal promise并拒绝它

Angular - return $modal promise and reject it

本文关键字:拒绝 promise modal 返回 Angular-      更新时间:2023-09-26

我正试图编写一个函数,打开一个有角度的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;
}

请参阅$q上的文档。