Promise、$mdDialog 和操作顺序

Promises, $mdDialog, and order of operations

我有一个带有登录页面的 angular 应用程序,该应用程序应该在处理请求时显示加载对话框。如果在后端登录成功,我就没有问题,我很快就会转到内容页面。不幸的是,如果登录失败,加载对话框永远不会隐藏。

这是我的代码结构:

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

在我的输出中我看到:

login failed
hide
dialog created

我想知道我是不是误解了 promises 的工作原理,或者 $mdDialog 服务内部有什么东西正在处理某种超时。

then方法中可以放三个函数

你必须把你的“$mdDialog.hide();”在第二个功能中,而不是第三个。 第三个函数仅在您发出长请求并且想要指示请求的进度百分比时使用。

像这样的东西一定有用:

$http.post('/login', $scope.credentials).then(function success() {
        // go to content page
      }, function error(response) {
        console.log('login failed');
        $mdDialog.hide();
      });

如您在输出中所见,对话框仅在登录失败后创建。尝试在 "show" 操作完成后发出 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();
            });
        });
    };
}
]);