concatenate $ http.post请求
问题描述:
如何连接两个$ http(.post)请求,以便一个在另一个之后被调用? 这是我的功能,这似乎不工作。
$scope.signup = function() {
console.log("New user");
$http.post('/signup',{
email: this.email,
password: this.password
}).then(function success($http){
return $http.post('api/userData/init'); //error
}).then(function redirect($state){
return $state.go('profile');
});
}
答
您在第一个回调中优先于$http
。 then
函数需要一个将http调用的结果作为参数的函数。尝试:
$scope.signup = function() {
console.log("New user");
$http.post('/signup',{
email: this.email,
password: this.password
}).then(function(){
return $http.post('api/userData/init');
}).then(function(){
return $state.go('profile');
});
}
答
你错过了通过只是一个缺口
$scope.signup = function() {
console.log("New user");
$http.post('/signup',{
email: this.email,
password: this.password
}).then(function(data){
$http.post('api/userData/init').then(function(newData){
$state.go('profile');
});
});
}
答
或者你也可以在电话明确地使用$ Q承诺:
//$q needs to be injected in the controller or service
var q = $q.deffer();
$http.post('/signup',{
email: this.email,
password: this.password
}).then(function(data){
//on success
q.resolve(data);
}, function(){
//on fail
q.reject('Failed');
});
//second call after the first is done
q.promise.then(function(firstCalldata){
//if you need you can use firstCalldata here
$http.post('api/userData/init').then(function(newData){
$state.go('profile');
});
})
有什么错误?你需要在第二个帖子上有一个回调函数 - '.then(函数成功($ http){...' –