连接$ http.post请求

时间:2016-03-28 11:12:59

标签: javascript angularjs angular-promise

如何连接两个$ 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');
    });            

}

3 个答案:

答案 0 :(得分:2)

你错过了一个档次

$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');
        });
    });

}

答案 1 :(得分:1)

或者你也可以明确地在调用中使用$ q Promise:

//$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');
        });
    })

答案 2 :(得分:0)

您在第一个回调中覆盖了$httpthen函数需要一个以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');
    });            

}