我正在尝试构建我的第一个角度应用程序,我一直收到一个错误,即当我尝试将工厂保存到服务中时回调不是一个函数,所以我可以在应用程序的生命周期中使用它。
这是我到目前为止所拥有的
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 :(得分: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)
});
}
您必须始终验证您的参数并对其执行操作以确保错误处理,并确保脚本不会因意外错误而停止。