shi*_*har 0 javascript http angularjs
我正在使用AngularJS将表单数据发送到服务器.
app.controller("OrganizerReg", ["$scope","$http", function($scope,$http) {
$scope.userOrganizer = {};
$scope.processform = function() {
$http ({
method: 'POST',
url: 'http://52.11.67.77:3000/api/users',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify($scope.userOrganizer)
})
.success(function(response) {
console.log(response.user_id);
$scope.user_id = response.user_id;
})
$http ({
method: 'POST',
url : 'http://52.11.67.77:3000/api/users/'+$scope.user_id+'/accessTokens',
})
.success(function(response) {
console.log(response);
})
}
Run Code Online (Sandbox Code Playgroud)
为了获得访问令牌,我需要发送一个POST请求.来自第一个HTTP请求的响应给出了user_id生成访问令牌所需的响应.问题是每当我发送请求时,$scope.user_id标头中的返回值都是未定义的.如何设置我的$scope.user_id全局,以便它可以被另一个HTTP请求使用.
编辑 我读了重复的问题,但它仍然没有帮助我.
使用promise chain来一个接一个地调用请求
function firstReq(){
return $http({
method: 'POST',
url: 'http://52.11.67.77:3000/api/users',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify($scope.userOrganizer)
})
}
function secondReq(){
return $http({
method: 'POST',
url : 'http://52.11.67.77:3000/api/users/' +$scope.user_id + '/accessTokens',
})
}
$scope.processform = function() {
firstReq()
.then( function( response )
{
console.log(response.data.user_id);
$scope.user_id = response.data.user_id;
return secondReq();
})
.then(function(response){
console.log(response.data);
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
609 次 |
| 最近记录: |