2016-11-17 52 views
1

我一直使用簡單的http方法返回的諾言很長一段時間。但我需要首先鏈接多個API調用並處理數據並返回該數據。問題我目前正在執行的是工廠沒有回覆承諾,因此不等待數據並執行控制器的下一行。合併多個API調用和處理後從工廠方法返回承諾

app.factory('mytestService', ['$http', function($http){ 
    getSomeDataById: function(id){ 
    var userAllProjects = []; 
    var myHelperService = this.getSecondData; 
    this.getFirstData(id).then(function(response){ // first api call 
     var idObjectValue = response['result'][0]['id']; 
     myHelperService(idObjectValue).then(function(response){ //second api call 
      userAllProjects= response['projectList'] 
     }); 
    }); 
    return userAllProjects 
    } 
]); 

現在控制器,當我做:

$scope.allProjects = mytestService.getSomeDataById(1234); 
console.log($scope.allProjects); 

控制檯打印不確定的。我知道這是因爲它不會等待服務完成並刪除下一行。

我是小角度承諾的新手,所以不知道如何處理。任何人都可以在這裏幫我。 如果您需要更多信息,請讓我知道。

+0

功能'getSomeDataById'全部過程後,沒有返回 – Weedoze

+0

它返回userAllProjects。 – undefined

+0

它不等待請求完成 – Weedoze

回答

-1

請嘗試下面的代碼。

getSomeDataById: function(id){ 
    var userAllProjects = $q.defer(); 
    var myHelperService = this.getSecondData; 
    this.getFirstData(id).then(function(response){ // first api call 
    var idObjectValue = response['result'][0]['id']; 
    myHelperService(idObjectValue).then(function(response){ //second api call 
     userAllProjects.resolve(response['projectList']) 
    }); 
    }); 
    return userAllProjects.promise; 
} 

這個想法是,你先創建一個延遲對象,然後返回承諾。當數據可用時,您解析延遲對象,數據將在您的控制器中可用。

注意:您將需要添加的依賴$q

編號:https://docs.angularjs.org/api/ng/service/$q

+0

我認爲那就是我一直在尋找的東西。你拯救了我的日子@Vivek。謝謝 – undefined

0

您可以使用then你的控制器內,而不是

app.factory('mytestService', ['$http', function($http) { 
    getSomeDataById: function(id) { 
     var myHelperService = this.getSecondData; 
     return this.getFirstData(id); 
    }, 
    secondApiCall : function(idObjectValue){ 
     return myHelperService(idObjectValue); 
    } 
}]); 

控制器

mytestService.getSomeDataById(1234).then(function(response){ 
    mytestService.secondApiCall(response['result'][0]['id']).then(function(response2){ 
    $scope.allProjects = response.data; 
    }) 
}); 
3

介紹Promise Chaining,它通常優於創造新deferred

getSomeDataById: function(id){ 
    var userAllProjects = []; 
    var myHelperService = this.getSecondData; 

    // returning promise rather than creating a new one, 
    // to prevent unresolved promise if one of the calls in the chain gets rejected 
    return this.getFirstData(id).then(function(response){ // first api call 
     var idObjectValue = response['result'][0]['id']; 
     return myHelperService(idObjectValue); //second api call 
     // instead of writing .then here, 
     // it can be moved to the outer layer for easy reading 

    }).then(function(response){ 
     userAllProjects = response['projectList']; 
     // return something you need to use in .then of getSomeDataById() here 
    }); 
});