我正在制作移动应用,我有一个处理用户登录的控制器。它进行http调用(当前为localhost)以检查用户是否有效。出于某种原因,它不会触发$ http呼叫,控制台也没有说它失败了。我是AngularJS的新手,我可能在我的代码中犯了初学者错误。我将AngularJS与Ionic Framework结合使用。
这是我的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 :(得分:1)
尝试从$ http请求中删除cache: $templateCache
。