如何强制事件等待解决 Angular.js 中的承诺?
how to force an event to wait for resolving a promise in Angular.js?
我有一个 angular-ui-路由器事件 '$stateChangeStart':
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
self.onUrlChange_(event);
});
和我的 onUrlChange_ 函数,例如:
function onUrlChange_(event) {
ModalDialog.show('confirm', { //this is promise
bodyContent: {
i18n: 'forms.unsavedConfirmMessage'
}
}).then(function() {}, function () {
event.preventDefault();
})
}
所以,我只想在 promise 被拒绝时阻止事件。但是这段代码不起作用,因为事件继续执行并且不等待承诺。
您的代码略有不同。这种做法基本上是先取消事件再做提示。如果提示成功,则再次手动触发状态更改事件。
一个单独的布尔变量会跟踪您是否已经提示用户并防止您陷入循环。如果您有任何问题,请告诉我。
//Have an outer variable to check if user has already been shown the modal prompt
var isWarned=false;
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if (isWarned === false) {
//Cancel the original event
event.preventDefault();
ModalDialog.show('confirm', {
bodyContent: {
i18n: 'forms.unsavedConfirmMessage'
}
}).then(function() {}, function() {
//Mark the isWarned flag so user is not warned again.Resume the navigation
isWarned = true;
$state.go(toState.name, toParams);
})
}
});
我有一个 angular-ui-路由器事件 '$stateChangeStart':
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
self.onUrlChange_(event);
});
和我的 onUrlChange_ 函数,例如:
function onUrlChange_(event) {
ModalDialog.show('confirm', { //this is promise
bodyContent: {
i18n: 'forms.unsavedConfirmMessage'
}
}).then(function() {}, function () {
event.preventDefault();
})
}
所以,我只想在 promise 被拒绝时阻止事件。但是这段代码不起作用,因为事件继续执行并且不等待承诺。
您的代码略有不同。这种做法基本上是先取消事件再做提示。如果提示成功,则再次手动触发状态更改事件。
一个单独的布尔变量会跟踪您是否已经提示用户并防止您陷入循环。如果您有任何问题,请告诉我。
//Have an outer variable to check if user has already been shown the modal prompt
var isWarned=false;
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if (isWarned === false) {
//Cancel the original event
event.preventDefault();
ModalDialog.show('confirm', {
bodyContent: {
i18n: 'forms.unsavedConfirmMessage'
}
}).then(function() {}, function() {
//Mark the isWarned flag so user is not warned again.Resume the navigation
isWarned = true;
$state.go(toState.name, toParams);
})
}
});