2014-03-19 26 views
1

我正在構建一個使用Parse.com作爲臨時後端的原型應用程序。

這就是Parse在請求發生時如何構造返回的數據。

{ 
     "results": [ 
     { 
      "playerName": "Jang Min Chul", 
      "updatedAt": "2011-08-19T02:24:17.787Z", 
      "cheatMode": false, 
      "createdAt": "2011-08-19T02:24:17.787Z", 
      "objectId": "A22v5zRAgd", 
      "score": 80075 
     }, 
     { 
      "playerName": "Sean Plott", 
      "updatedAt": "2011-08-21T18:02:52.248Z", 
      "cheatMode": false, 
      "createdAt": "2011-08-20T02:06:57.931Z", 
      "objectId": "Ed1nuqPvcm", 
      "score": 73453 
     } 
     ] 
    } 

我有一個工廠,看起來像這樣

app.factory('eventFactory', ['$resource', function($resource){ 
      return $resource('https://api.parse.com/1/classes/Events', {}, 
       { 'get': {method:'GET'}, 
        'save': {method:'POST'}, 
        'query': {method:'GET', isArray:false}, 
        'remove': {method:'DELETE'}, 
        'delete': {method:'DELETE'} 
       }); 

      } 
     ]); 

我的控制器看起來是這樣的:

app.controller('currentTradeshowsController', function($scope, eventFactory){ 



     var testSave = eventFactory.get(); 
        console.log(testSave); 

     console.log(testSave.results); 

    }); 

爲 'testSave' 第一的console.log看起來是這樣的:

Imgur

where testSave.results返回undefined。

我認爲我可以通過這種方式訪問​​所有的對象嗎?

缺少什麼我在這裏?

任何幫助,非常感謝。

+1

您的.get()返回一個承諾對象。要獲取實際的數據,你必須傳遞一個回調,如.get(function(response){console.log(response);});或use.then(function()... –

回答

1

儘管$resource在抽象方面做得非常好,但事實仍然是,由於它通過HTTP調用工作,所以它異步運行,必須編寫代碼以便在語義上處理它。 The documentation expresses this.

var testSave = eventFactory.get().success(function() { 
    console.log(testSave); 
}); 

不幸的是,角文檔不說清楚,但我想上面會工作。可能的備選方案如下:

.get(function() { 
.get({}, function() { 
.get().then(function() { 
.get().$promise.then(function() { 

找到一個適用於您的工作方式,並且最適合您。這個想法是成功回調和任何依賴於成功請求的東西都需要在這個函數中。