2016-09-16 68 views
0

我已經 我使用AngularJS無法以推動數據到列表

這裏一個列表,它包含對象的列表,這樣,現在我想多一個對象添加到每個列表中的主列表是我想

$scope.mediaList = []; 

$scope.getTheProfile = function(data){ 
     for(var i in data) 
     { 
      ProfileService.getByHandle(data[i].handle,function(profiledata) 
       { 
        $scope.mediaList[i].displayName = profiledata.name.displayName 
       }, 
       function(data , status){ 
        console.log("In Error"); 
        if(status == '400'){ 
         $scope.errors.push(data["ERROR"]) 
        } 
       }, 
       function(data , status){ 
        console.log("In forbidden") 
       }) 
     } 
     alert($scope.mediaList[0].displayName) 
    } 

,所以我試圖顯示名添加到列表 現在的問題是我不能夠在警報 得到值,如果該警報是內部ProfileService.getByHandle功能那麼我的代碼獲得價值

這是功能getByHandle

this.getByHandle = function(handle, successCB, errorCB, forbiddenCB) { 
     console.log("In Profile Service for fetching the profile by handle: "+handle); 

     HttpCommunicationUtil.doGet(apiConstants["profile"]["getByHandle"]+"/"+handle, successCB, errorCB, forbiddenCB); 
    }; 
+0

你傳入3個參數傳遞給getByHandle,其中兩個是功能。無法得到爲什麼需要。你可以發佈getByHandle方法的代碼嗎? –

+0

@SaurabhTiwari現在查看更改 – raja

+0

您是否在alert中使用了「undefined」? –

回答

0

getByHandle,看來你正在使用HttpCommunicationUtil.doGet異步 HTTP請求。

什麼情況是這樣的:for循環會使HTTP電話和觸發此警報alert($scope.mediaList[0].displayName)無需等待getByHandle的反應,因爲它是一個異步請求。

因此,當您嘗試到alert時,由於行#1,將存在$scope.mediaList的空數組[]。所以$scope.mediaList[0].displayName會產生錯誤,說無法得到undefined的displayName。

您可以在ProfileService.getByHandle中返回promises,當它解決時使用.then更新您的變量。

如果您可以發佈HttpCommunicationUtil.doGet的代碼,它會更有用。

編輯: 沒有HttpCommunicationUtil.doGet,我給你如何做一個通用的方法的想法。

服務:

this.getByHandle : function(params) { 
    return $http.get('/api/endpoint'); 
} 

控制器:

ProfileService.getByHandle(params).then(function(data){ 
    //use data to push response in $scope.mediaList[i] 
}); 
+0

嘿,我是新來的這可以幫助我,我應該添加承諾 – raja

+0

$ http本身是一個承諾..所以你可以更好地返回$ http承諾本身。不需要額外的$ q –