2016-06-07 75 views
0

我有一个角度的应用程序与一个登录页面应该显示加载对话框,而请求正在处理。如果登录在后端成功,我就没有问题了,然后我马上离开内容页面。不幸的是,如果登录失败,加载对话框不会被隐藏。

这里是我的代码的结构:我想知道如果我也许误解的承诺是如何工作的或可能存在于内部的东西

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服务。

+1

你应该用角加载条http://chieffancypants.github.io/angular-loading-bar/所有'$ http'请求到后端。 – nextt1

+0

你是否期待那第二个()作为终止函数?如果是这样......将其更改为finally(function(){});请参阅https://docs.angularjs.org/api/ng/service/$q以了解Promise API部分。 – Zach

+0

@Zach我也试过,但在对话框创建并显示之前仍然被调用 – pulse0ne

回答

4

正如你在输出看到的只是登录失败后创建的对话框。尽量让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

0

在当时的方法,你可以把三个功能。

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

像这样的东西必须努力:

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

问题是,我没有使用进度函数,我使用了另一个'.then()',在post promises解析后调用。如果仔细观察我的代码,我没有传递任何进度参数 – pulse0ne

+0

实际上,这不是他在那里连接的第三个函数......然后他链接了一秒(),并将它设置为然后();.我会删除第二个,然后将其放入错误响应中,如Oreste Viron所示。 – Zach

+0

我也试过,它不起作用。在创建对话框之前调用'.hide()'并且显示 – pulse0ne