2016-09-16 51 views
0

我的工廠代碼無法從工廠返回值服務angularJS

.factory('appData', ['connectionManager', function($connectionManager) { 
    return { 
     getAppDataItem: function(apiName, params) { 
      console.log('Getting value...'); 
      $connectionManager.sendRequest({ 
       'apiName': apiName, 
       'params':{ 
        '@key': "'" + params['@key'] + "'" 
       } 
      }).then(function(res){ 
       console.log('Retrieved data ', res.data); 
       return res.data; 
      }); 
     } 
    } 
}]); 

我的服務代碼

  var x = appData.getAppDataItem('getItemFromAppData', { 
        '@key': 'last_emp_id' 
       }); 
      console.log(x); 

我想通過.then()工廠返回的值賦給var x在我的服務。但我無法做到。請幫幫我。我的價值高達.then()。之後,我無法將其傳遞給服務。

+0

你有什麼錯誤嗎? apiName是否清楚傳遞? – Aravind

+0

可能的重複[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

回答

1

的函數需要返回一個承諾:

.factory('appData', ['connectionManager', function($connectionManager) { 
    return { 
     getAppDataItem: function(apiName, params) { 
      console.log('Getting value...');     
      //$connectionManager.sendRequest({ 
      //return promise 
      return $connectionManager.sendRequest({ 
       'apiName': apiName, 
       'params':{ 
        '@key': "'" + params['@key'] + "'" 
       } 
      }).then(function(res){ 
       console.log('Retrieved data ', res.data); 
       return res.data; 
      }); 
     } 
    } 
}]); 

客戶端代碼應該使用承諾的.then方法來訪問數據。

var promise = appData.getAppDataItem('getItemFromAppData', { 
     '@key': 'last_emp_id' 
    }); 
promise.then(function (x) { 
    console.log(x); 
}); 
+0

非常感謝。有沒有其他方法可以做到這一點? 這是好的,但我想知道 –

+0

另一種方法是返回一個對象引用,稍後將填充數據。但是在那種情況下,我建議將promise作爲名爲'$ promise'的屬性添加到對象中。 – georgeawg