2015-09-28 50 views
0

我有角服務:返回的對象奇怪形成

/* App Module */ 
 
var triviaApp = angular.module('triviaApp', ['ngRoute', 'ngResource', 'ngCookies','ngAnimate', 'ui.bootstrap']); 
 
    
 
    triviaApp.service('GameService', ['$rootScope', '$log', '$http', '$resource', '$location', function($rootScope, $log, $http, $resource, $location) { 
 
    
 
    \t this.newGame = function(playerId, aiLevel, opponentId) { 
 
\t \t console.log('newGame - init'); 
 
\t \t 
 
\t \t return $http({ 
 
\t \t \t url: triviaAppConfig.rootAPIUrl + 'Players/' + playerId + '/Games?aiLevel=' + aiLevel + '&OpponentId=' + opponentId, 
 
\t \t \t method: "POST", 
 
\t \t \t }) 
 
\t \t \t .then(function(response) { \t \t \t \t 
 
\t \t \t \t return response.data; 
 
\t \t \t }, function(response) { 
 
\t \t \t \t $log.warn('Error in $http - getGames in controller...'); 
 
\t \t }); 
 
\t 
 
\t } 
 
    
 
    }]);

這裏是我的控制器調用我的服務,並將其附加到newGameBtn指令....

// HOME CONTROLLER 
    triviaApp.controller('HomeController', ['$rootScope', '$scope', '$http', '$cookies', 'GameService', '$log', 
    function($rootScope, $scope, $http, $cookies, GameService, $log) { 

      // Initiate New Game Function 
     $scope.newGameBtn = function(emailId, aiLevel, opponentId) { 
     $scope.gameObj = GameService.newGame(emailId, aiLevel, opponentId); 
      console.log($scope.gameObj); 

     } 


]); 


</script> 
<div class="col-md-6 new-game-button"> 
     <a href="" ng-click="newGameBtn(emailId, 'none', 0)"> 
      <img src="/img/home/player-vs-player.png" width="256" height="161" alt="Player Vs Player"> 
      <p>New auto-matched Game</p> 
     </a> 
    </div> 

我運行中的問題是,$ scope.gameObj是回來爲:現在

d {$$state: Object} 
 
$$state: Object 
 
status: 1 
 
value: Object 
 
ActivePlayer: 40 
 
ConsecutiveAnswerCount: 0 
 
ConsecutiveAwardsCount: 0 
 
EndTime: "0001-01-01T00:00:00" 
 
GameId: 1168 
 
GameRound: 0 
 
IsAwardRound: false 
 
IsEndOfTurnRound: false 
 
IsGameOverRound: false 
 
Player1: Object 
 
Player1AnswerSeconds: 0 
 
Player1Awards: Array[0] 
 
Player1Score: 0 
 
Player2: Object 
 
Player2AnswerSeconds: 0 
 
Player2Awards: Array[0] 
 
Player2Score: 0 
 
StartTime: "2015-09-28T15:45:09.5246982Z" 
 
Status: "InProgress" 
 
WinningPlayer: 0 
 
__proto__: Object 
 
__proto__: Object 
 
__proto__: d

,從閱讀圍繞這聽起來像我得到的承諾回來,不是對象,但我有的問題是如何重寫服務和控制器來將$ scope.gameObj設置爲我的對象數據而不是承諾?

+0

這肯定看起來像你的遊戲資料...一個承諾不有像「Player1Score」等屬性。 –

+0

這是我的數據,但它被埋在d> $$ state> value對象的3層深處,而不是根對象。 – TWLATL

回答

1

使服務回報承諾:

this.newGame = function(playerId, aiLevel, opponentId) { 
    return $http({ 
    url: triviaAppConfig.rootAPIUrl + 'Players/' + playerId + '/Games?aiLevel=' + aiLevel + '&OpponentId=' + opponentId, 
    method: "POST", 
    }); 
} 

,使您的控制器等待它的分辨率:

GameService.newGame(emailId, aiLevel, opponentId).then(function(response) { 
    $scope.gameObj = response.data; 
}); 
+0

這可以起作用,但是通過從服務中刪除.then的解析到控制器,我已經刪除了使用該服務將該對象傳送到其他控制器的功能。爲什麼當它在服務中時不能傳遞對象,而是在控制器中工作? – TWLATL