2016-03-28 74 views
0

如何連接兩個$ 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'); 
    });    

} 
+0

有什麼錯誤?你需要在第二個帖子上有一個回調函數 - '.then(函數成功($ http){...' –

回答

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

} 
+0

太棒了,這就是爲什麼!非常感謝你的解釋 – Ugo

+0

太棒了。那麼你可以接受我的回答:) – yarons

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

或者你也可以在電話明確地使用$ 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'); 
     }); 
    })