2015-10-15 38 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) 
     }); 

    } 

你必須始終驗證你的論點,並對其執行行動,以確保錯誤處理,並確保由於意外錯誤的腳本不會停止。

相關問題