[英]How to wait the return of a Callback function?
How to implement that use case properly: after the customer has confirmed an action I want to display a waiting screen until the callback function has been performed completely... 如何正确实现该用例:在客户确认一项操作后,我要显示一个等待屏幕,直到回调函数完全执行为止。
I've done the following but the REST call is performed after that the srv.hideLoadingScreen()
has been called... :-/ 我已经完成了以下操作,但是在调用srv.hideLoadingScreen()
之后执行了REST调用::-/
DialogService: DialogService:
srv.onApprove = function(callback){
srv.displayLoadingScreen();
callback();
srv.hideLoadingScreen();
};
Controller: 控制器:
ctrl.showConfirmModal = function(){
//...
if(approved){
DialogService.onApprove(function(){
ctrl.performAction();
});
}
};
ctrl.performAction = function(){
console.log('performAction');
if(angular.isDefined(ctrl.selectedNumberList)){
var numberList = {
nbList: ctrl.selectedNumberList
};
MyService.launch(numberList, function(response){ // REST call
console.log('call ok');
}, function(error){
console.log('error');
});
}
};
ctr.perfomAction()
更新:当前,我选择了避免回调的回调的解决方案:关闭ctr.perfomAction()
的等待面板
MyService.launch(numberList, function(response){ // REST call console.log('call ok'); DialogService.hideLoadingScreen(); }, function(error){ console.log('error'); DialogService.hideLoadingScreen(); });
You can just use the $http
service to return a Promise. 您可以只使用$http
服务来返回Promise。
Asynchronous actions aren't returned until they are completed and the call stack is clear. 异步操作只有在完成并清除调用堆栈后才返回。 Since we'll leave scope before they are returned you can use a Promise to ensure you get the value back. 由于我们将在退还范围之前保留范围,因此您可以使用Promise来确保您获得价值。
app.service('MyService', function($http) {
this.launch = function launch() {
return $http({ method: 'GET', url: '/endpoint' });
};
}
app.controller('MyCtrl', function(MyService) {
MyService.launch()
.then(function(response) {
});
});
The same can also be achieved with the $q
service to return a promise for any type asynchronous call. $q
服务可以为任何类型的异步调用返回承诺,也可以实现相同的目的。
Use Angular-busy . 使用Angular-busy 。 This way should work for you: 这种方式应该为您工作:
APPLY 应用
bower install angular-busy --save
index.html
将dist / angular-busy.js和dist / angular-busy.css添加到index.html
cgBusy
as a module dependency for your module. 将cgBusy
添加为模块的模块依赖项。 angular.module('your_app', ['cgBusy']);
CONTROLLER CONTROLLER
$scope.myPromise = MyService.launch(numberList, function(response){ // REST call...
PARTIAL 局部
<div cg-busy="{promise:myPromise,
message:'Loading',
backdrop:false,
templateUrl:'myAwesomeTemplate.html',
delay:300,
minDuration:700} ">
</div>
EDIT FOR YOUR COMMENT: 编辑您的评论:
What about something like this? 那这样的东西呢?
MyService.launch(numberList, function(response){
-----> $scope.myPromise = console.log('call ok'); <--------
}, function(error){
console.log('error');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.