承诺,$ mdDialog和操作顺序
问题描述:
我有一个角度的应用程序与一个登录页面应该显示加载对话框,而请求正在处理。如果登录在后端成功,我就没有问题了,然后我马上离开内容页面。不幸的是,如果登录失败,加载对话框不会被隐藏。
这里是我的代码的结构:我想知道如果我也许误解的承诺是如何工作的或可能存在于内部的东西
login failed
hide
dialog created
:
app.controller('loginController', [
'$scope',
'$http',
'$mdDialog',
function($scope, $http, $mdDialog) {
var showLoading = function(message) {
$mdDialog.show({
templateUrl: '../views/loading.html',
controller: function($scope) {
console.log('dialog created');
$scope.message = message;
}
});
};
$scope.credentials = {
username: '',
password: ''
};
$scope.handleLogin = function() {
showLoading('Logging in...');
$http.post('/login', $scope.credentials).then(function success() {
// go to content page
}, function error(response) {
console.log('login failed');
}).then(function() {
console.log('hide');
$mdDialog.hide();
});
};
}
]);
在我的输出我看到正在处理某种超时的$mdDialog
服务。
答
正如你在输出看到的只是登录失败后创建的对话框。尽量让http请求“秀”行动结束后:
app.controller('loginController', [
'$scope',
'$http',
'$mdDialog',
function($scope, $http, $mdDialog) {
var showLoading = function(message, onShown) {
$mdDialog.show({
templateUrl: '../views/loading.html',
controller: function($scope) {
console.log('dialog created');
$scope.message = message;
},
onComplete:onShown
});
};
$scope.credentials = {
username: '',
password: ''
};
$scope.handleLogin = function() {
showLoading('Logging in...', function(){
$http.post('/login', $scope.credentials).then(function success() {
// go to content page
}, function error(response) {
console.log('login failed');
}).finally(function() {
console.log('hide');
$mdDialog.hide();
});
});
};
}
]);
+0
谢谢,这个完美的作品 – pulse0ne
答
在当时的方法,你可以把三个功能。
你必须把你的“$ mdDialog.hide();”在第二个功能中,不是第三个功能。 第三个函数仅在您发起长时间请求时使用,并且您希望指示请求的进度百分比。
像这样的东西必须努力:
$http.post('/login', $scope.credentials).then(function success() {
// go to content page
}, function error(response) {
console.log('login failed');
$mdDialog.hide();
});
你应该用角加载条http://chieffancypants.github.io/angular-loading-bar/所有'$ http'请求到后端。 – nextt1
你是否期待那第二个()作为终止函数?如果是这样......将其更改为finally(function(){});请参阅https://docs.angularjs.org/api/ng/service/$q以了解Promise API部分。 – Zach
@Zach我也试过,但在对话框创建并显示之前仍然被调用 – pulse0ne