2014-09-23 72 views
0

我正在製作移動應用程序,並且我有一個處理用戶登錄的控制器。它會進行http調用(當前爲localhost)來檢查用戶是否有效。由於某種原因,它不會觸發$ http調用,並且控制檯沒有提到它的失敗。我是AngularJS的新手,我可能在我的代碼中犯了一個初學者的錯誤。我正在使用帶有Ionic Framework的AngularJS。

這是我的LoginController:

.controller('LoginCtrl', ['$scope', '$ionicPopup', 'User', '$window', '$http', '$templateCache', function($scope, $ionicPopup, User, $window, $http, $templateCache){ 
    $scope.authUser = function(){ 
     console.log('authUser initialized'); 
     var email = document.getElementById('User_email'); 
     var password = document.getElementById('User_password'); 
     console.log('email=' + email.value); 
     console.log('password=' + password.value); 

     console.log('logging in...'); 
     if(email.value == '' || password.value == ''){ 
      var alertPopup = $ionicPopup.alert({ 
       title: 'Failed to login', 
       template: 'Both fields need to be filled.' 
      }); 
      alertPopup.then(function(res){ 
       console.log('Both fields need to be filled.'); 
      }); 
     } else { 
      console.log('Contacting API server...'); 
      $scope.$apply(function(){ 
       $http({ 
        method: 'POST', 
        url: 'http://api.tb.local/api.php', 
        data: { 'action': 'user/auth', 'email': email.value, 'password': password.value }, 
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
        cache: $templateCache 
       }). 
       success(function(response){ 
        console.log('Response success'); 
        console.log(response); 
        if(response.valid){ 
         console.log('Login success. Redirecting to welcome page...'); 
         $window.location.href = '#/welcome'; 
        } else { 
         var alertPopup = $ionicPopup.alert({ 
          title: 'Failed to login', 
          template: 'Wrong credentials. Please try again.' 
         }); 
         alertPopup.then(function(res){ 
          console.log('Wrong credentials. Please try again.'); 
         }); 
        } 
       }). 
       error(function(response){ 
        var requestFailDialog = $ionicPopup({ 
         title: 'Internal Error', 
         template: 'The server encountered an unknown error.' 
        }); 
        requestFailDialog.then(function(res){ 
         console.log('Internal Error: ' + response); 
        }); 
       }); 
      }); 
     } 
    } 
}]) 

我在控制檯中看到的最後一件事是Contacting API server...

我手動測試了我的API,它就像它應該返回一個json { "valid": true }

+0

爲什麼你在$ scope中有整個$ http調用?$ apply({})?嘗試刪除。 – 2014-09-23 06:20:42

+0

@TomErikStøwer我從這個問題取$ scope。$ apply({}):http://stackoverflow.com/questions/16299362/angular-js-http-post-not-working-no-error因爲我以爲我的問題是因爲這個。但無論它有沒有它,它仍然不起作用。 – 2014-09-23 06:22:28

+0

在控制檯中,'響應成功'正在打印? – 2014-09-23 06:25:45

回答

1

嘗試從$ http請求中刪除cache: $templateCache

相關問題