我一直在尝试使用离子angularjs中的$ http请求连接到后端服务器。我想使用API注册用户。有人能告诉我我的代码有什么问题吗?这是我的controller.js
angular.module('app.Auth', [])
.factory('Auth', ['$q', '$http', '$localStorage', 'URL', function($q, $http, $localStorage, URL) {
return {
register: function(data, success, error) {
$http.post(URL.api + 'register', data).success(success).error(error)
}
};
}])
.controller('SignupCtrl', function($scope, $rootScope, $timeout, $stateParams, ionicMaterialInk,Auth,$localStorage,$state,Auth,URL) {
$scope.signupError = function(msg){
if(msg.status == false){
$scope.errors = msg.errors;
}else{
$scope.errors = ['Error accessing API.'];
}
};
$scope.signupSuccess = function(response){
if(response.status==false){
$scope.errors = response.errors;
}else{
alert("success!");
}
};
$scope.user = {
firstname:'',
middlename:'',
lastname:'',
password: '',
email: ''
};
$scope.signupEmail = function(){
Auth.register($scope.user,$scope.signupSuccess,$scope.signupError);
};
});
这是我的signup.html
<ion-view view-title="Sign Up" name="signup">
<ion-content>
<div class="list">
<div ng-if="errors.length > 0" class="error_bg" ng-repeat="error in errors">
<p class="error" ng-bind="error"></p>
</div>
<label class="item item-input item-floating-label">
<span class="input-label">First Name</span>
<input type="text" placeholder="First Name" style="color:purple; font-size:18px" ng-model="user.firstname">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Middle Name</span>
<input type="text" placeholder="Middle Name" style="color:purple; font-size:18px" ng-model="user.middlename">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Last Name</span>
<input type="text" placeholder="Last Name" style="color:purple; font-size:18px" ng-model="user.lastname">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Email Address</span>
<input type="text" placeholder="Email Address" style="color:purple; font-size:18px" ng-model="user.email">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Password</span>
<input type="password" placeholder="Password" style="color:purple; font-size:18px" ng-model="user.password">
</label>
</div>
<button class="button button-block button-royal" style="background-color:blue" ng-click="signupEmail()">Continue</button>
答案 0 :(得分:0)
注意$http.post
的正确sintax。
实际上,$http.post()
返回 promise ,其方法then()
有两个参数(成功和错误处理程序),因此您的HTTP请求注册服务应该被重写从:
$http.post(URL.api + 'register', data).success(success).error(error);
为:
$http.post(URL.api + 'register', data).then(success, error);
对于Angular中的承诺,请参阅https://docs.angularjs.org/api/ng/service/ $ q