2016-06-07 35 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