2015-10-15 39 views
0

我试图构建我的第一个角度应用程序,当我试图将我的工厂保存到服务中时,我不断收到一个错误,该回调不是函数,因此我可以将其用于应用程序的生命。TypeError:回调不是AngularJS中的函数应用

这里是我迄今为止

angular.module('games', ['ui.router', 'ui.bootstrap']) 
.config(function($urlRouterProvider, $locationProvider, $stateProvider) { 
    // For any unmatched url, redirect to /state1 
    $urlRouterProvider.otherwise("/"); 
    //take out # 
    $locationProvider.html5Mode({ 
     enabled: true, 
     requireBase: false 
    }); 

    // Now set up the states 
    $stateProvider 
     .state('games', { 
      url: "/", 
      templateUrl: "/static/app/list.html", 
      controller: 'gamesCtrl' 
     }) 
    $stateProvider 
     .state('game', { 
      url: "/games/:title", 
      templateUrl: "/static/app/page.html", 
      controller: 'pageCtrl' 
     }) 
}) 

.controller('gamesCtrl', ['$scope', '$state', 'gamesService', 
    function($scope, $state, gamesService) { 
     $scope.$state = $state; 
     $scope.games = null; 

     function init() { 
      gamesService.getGames().success(function(games) { 
      $scope.games = games.data; 
      console.log($scope.games.data) 
      }); 

     } 
     init(); 
    } 

]) 

.service('gamesService', ['gamesFactory', 
    function(gamesFactory) { 
     //grab the list of games on load 
     var gamesList = []; 
     gamesFactory.getGames().success(function(games) { 
      gamesList = games 
     }); 

     this.getGames = function(callback){ 
      callback(gamesList); 
     } 
    } 
]) 

.factory('gamesFactory', function($http) { 
    var factory = {}; 
    factory.getGames = function() { 
     return $http.get('/games.json'); 
    }; 
    return factory; 
}); 

我的错误是在这里

.service('gamesService', ['gamesFactory', 
    function(gamesFactory) { 
     //grab the list of games on load 
     var gamesList = []; 
     gamesFactory.getGames().success(function(games) { 
      gamesList = games 
     }); 

     this.getGames = function(callback){ 
      callback(gamesList); 
     } 
    } 
]) 

存在的任何帮助将不胜感激。

+0

只要可能,您应该考虑使用'.then()'而不是'.success()'加上'$ http'。 – Claies

回答

0

也许你应该这样做。 getGames期望回调,并且由于你通过它,它是未定义的。 GameFactory和GameService都有getGames命名的功能,这是令人困惑的,这可能会导致你犯一个小错误。 gameService中的函数getGames需要回调,并且没有检查是否已通过回调。

步骤1:

变化gameService的this.getGames功能。

this.getGames = function(callback){ 
    if(callback and typeof callback==='function'){ 
     callback(gamesList); 
    } 
    } 

步骤2

我基于问题你的 “成功” 的尝试猜测这一点。

function init() { 
     gamesService.getGames(function(games) { 
     $scope.games = games.data; 
     console.log($scope.games.data) 
     }); 

    } 

你必须始终验证你的论点,并对其执行行动,以确保错误处理,并确保由于意外错误的脚本不会停止。

相关问题