【发布时间】:2015-12-14 00:37:53
【问题描述】:
我正在尝试在AngularJS 中发送请求以获取用于用户注册的令牌。获得令牌后,我将使用令牌发送另一个请求来注册用户。
但是第一个请求有效并且我获得了令牌,但第二个无效。
代码
facebookExample.controller('registerController', function($scope, $http, $localStorage, $location) {
$scope.data = {};
$scope.getToken = function() {
$http.post('http://you-serve.org/api.php?action=createaccount&format=json&name=' + $scope.data.username + '&email=' + $scope.data.email + '&realname=' +
$scope.data.firstname + ' ' + $scope.data.lastname +
'&mailpassword=false&reason=Fun_and_profit&language=en&token').then(
function(response) {
return response.data.createaccount.token;
}
// End success
,
function() {
alert('error');
} // End error
); //End then
} // End getToken
$scope.register = function(myToken) {
$http.post('http://you-serve.org/api.php? action=createaccount&format=json&name=' +
$scope.data.username + '&email=' +
$scope.data.email + '&realname=' +
$scope.data.firstname + ' ' +
$scope.data.lastname +
'&mailpassword=false&reason=Fun_and_profit&language=en&token=' + myToken).then(
function(response) {
alert("Registration successful ! You can log in now " + response.data.createaccount.username);
},
function(response) {
alert(response.data.error.info);
}); //End then
} //End register
$scope.signup = function() {
register(getToken);
} // End sign up
}); // End controller
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<ion-view ng-controller="registerController" title="Sign Up" view-title="Sign Up" name="login-view">
<ion-content class="padding">
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="data.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="data.email">
</label>
<label class="item item-input">
<input type="text" placeholder="First Name" ng-model="data.firstname">
</label>
<label class="item item-input">
<input type="text" placeholder="Last Name" ng-model="data.lastname">
</label>
<label class="item item-input">
<input type="text" placeholder="City" ng-model="data.city">
</label>
<label class="item item-input">
<input type="text" placeholder="Country" ng-model="data.country">
</label>
</div>
<button class="button button-block button-calm" ng-click="register(getToken())">Sign Up</button>
</ion-content>
</ion-view>
有人知道我该怎么做吗?
【问题讨论】:
-
您可以创建一个局部变量,将令牌分配给局部变量。然后将其传递给第二个 http 请求。
-
由于
$http调用是异步的,你必须在第一个成功中调用第二个请求。
标签: javascript html angularjs http angularjs-http