pulse0ne pulse0ne - 5 months ago 77
AngularJS Question

Promises, $mdDialog, and order of operations

I've got an angular app with a login page that's supposed to show a loading dialog while the request is being processed. If the login succeeds on the backend, I've got no problem and I'm whisked away to the content page. Unfortunately, if the login fails, the loading dialog never gets hidden.

Here's the structure of my code:

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();
});
};
}
]);


In my output I see:

login failed
hide
dialog created


I'm wondering if I'm maybe misunderstanding how promises work or maybe there's something internally in the
$mdDialog
service that is working on a timeout of some sort.

Answer

As you see in output the dialog created only after the login failure. Try to make http request after "show" action is finished:

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();
            });
        });
    };
}
]);