从Service AngularJS传递数据

时间:2014-02-18 16:54:31

标签: javascript angularjs

亲爱的,我在我的$ scope范围内遇到问题,或者我应该怎么做。

我正在从我的服务中成功检索数据但是我在访问$ scope.players和$ scope.tournament方面遇到了麻烦,我认为它与服务调用内部有关。如果我在服务调用中调用console.out(),一切都很好。如何才能访问服务调用内的数据。

版本1: 这里控制台日志只是声明未定义。

.controller('SelectCtrl', ['$scope','$stateParams', '$location', '$window','playerService','tournamentService', function ($scope, $stateParams, $location, $window, playerService, tournamentService) {

     init();
     function init() {

         playerService.getPlayers().then(function (data) {
             $scope.players = [];
             angular.forEach(data, function (player, index) {
                 $scope.players.push(player.info);
             });
         });

         tournamentService.getTournaments().then(function (data) {
             var result = data.filter(function (element) {
                 if (element.ID == $stateParams.id) {
                     return true;
                 } else {
                     return false;
                 }
             });
             $scope.tournament = result;
         });
     };

     console.log($scope.tournament);//undefined
     console.log($scope.players); //undefined
}

版本2:, 这里控制台日志只是简单地说明对象{然后:函数,catch:函数,最后:函数} 这不是我想要的数据,我希望数据能够在我的视图中显示它。 / p>

.controller('SelectCtrl', ['$scope','$stateParams', '$location', '$window','playerService','tournamentService', function ($scope, $stateParams, $location, $window, playerService, tournamentService) {

     init();
     function init() {

         $scope.players = playerService.getPlayers().then(function (data) {
             $scope.players = [];
             angular.forEach(data, function (player, index) {
                 $scope.players.push(player.info);
             });
         });

        $scope.tournament = tournamentService.getTournaments().then(function (data) {
             var result = data.filter(function (element) {
                 if (element.ID == $stateParams.id) {
                     return true;
                 } else {
                     return false;
                 }
             });
             $scope.tournament = result;
         });
     };

     console.log($scope.tournament);//Object {then: function, catch: function, finally: function}

     console.log($scope.players);//Object {then: function, catch: function, finally: function}

}

非常感谢您的帮助!

服务:

.factory('playerService', function ($http,$q) {
    return {
        getPlayers: function () {
            //return the promise directly.
            var deferred = $q.defer();
            $http.get(webServiceUrl + 'api/Player/GetAllPlayers')
                      .success(function (data) {
                          //resolve the promise as the data
                          deferred.resolve(data);
                      }).error(function () {
                          deferred.reject();
                      });
            return deferred.promise;
        }
    }

})

.factory('tournamentService', function ($http,$q) {
    return {
        getTournaments: function () {
            //return the promise directly.
            var deferred = $q.defer();
            $http.get(webServiceUrl + 'api/Tournament/GetAllTournaments')
                      .success(function (data) {
                          //resolve the promise as the data
                          deferred.resolve(data);
                      }).error(function () {
                          deferred.reject();
                      });
            return deferred.promise;
        }
    }

})

部分观点:

  <h1 style="display: inline-block; margin-left:15px;">Enter <i>{{tournament.Name}}</i></h1>
        <div class="row">
            <div class="selectinforow">
                <div class="col-xs-2 selectinfo">
                    <span>{{tournament.EntryFee}}$</span></br>
                    <span>Entry Fee</span>
                </div>
                <div class="col-xs-2 selectinfo">
                    <span>{{tournament.Entries}}</span></br>
                    <span>Entries</span>
                </div>
                <div class="col-xs-2 selectinfo">
                    <span>{{tournament.Size}}</span></br>
                    <span>Max Size</span>
                </div>
                <div class="col-xs-2 selectinfo">
                    <span>{{tournament.StartTime}}</span></br>
                    <span>Start Date</span>
                </div>
                <div class="col-xs-2 selectinfo">
                    <span>{{tournament.Entryfee*tournament.Entries}}$</span></br>
                    <span>Winnings</span>
                </div>
            </div>
        </div>

2 个答案:

答案 0 :(得分:2)

因此,如果您仔细阅读代码,您会注意到您在以下行中使用了承诺:

tournamentService.getTournaments().then(function (data) {
   // [your data is set here - AFTER the service call runs]
}

// [your print is here - run BEFORE service call runs]

“then”语句的关键是它不会立即执行,而是在从服务调用返回数据时运行。换句话说,你的打印位置错误 - 我希望那里的值不确定。如果将console.log语句移动到promise(然后) - 我希望看到有效值。如果要验证事情是否正常,您还可以在浏览器调试器中设置断点以查看“then”函数中的值。希望这能让你走上正轨!

修改

承诺完成后,angular会自动更新视图。假设您在视图中有以下内容(仅作为示例):

<h1 ng-bind="tournament.Title">Default Text</h1>

当加载视图/页面时,您将看到“默认文本”。承诺完成后,如果已加载锦标赛,角度将自动更新“h1”,现在拥有该锦标赛的标题。发生这种情况是因为在promise完成后,angular会自动运行“$ apply()”。

答案 1 :(得分:0)

您的代码在promise响应之前执行。

如果您需要“程序性地”编码,则应$watch范围变量如下所示检测任何更改。

例如:

$scope.$watch('tournament', function() {
 console.log($scope.tournament);
}, true);