TypeError: Невозможно прочитать свойство 'getGames' из неопределенного

0

Я новичок в angularjs, и у меня эта проблема, похоже, не может понять.

Я вытаскиваю json-канал, по какой-то причине приложение возвращается неопределенным. Не уверен, что это связано с тем, что для получения корма json требуется немного, или что-то не так с моим кодом.

Ошибка, которую я продолжаю получать

TypeError: Cannot read property 'getGames' of undefined

Вот угловой javascript, который я написал.

angular.module('games', ['ui.router'])
.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'
        })
})

.controller('gamesCtrl', ['$scope', function($scope, $state, gamesFactory){
    $scope.$state = $state;
    $scope.games = null;
    function init() {
        gamesFactory.getGames().success(function(games) {
            $scope.games = games;
            console.log($scope.games.data)
        });

    }
    init();
}])

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

Выход json выглядит так:

{
  "data": [
    {
      "author": "ZeptoLab", 
      "categories": [
        "Classics", 
        "Puzzles"
      ], 
      "category": "Classics", 
      "creation": "2015-05-12T09:16:57.719Z", 
      "desc_de": null, 
      "desc_en": null, 
      "desc_es": null, 
      "desc_fr": null, 
      "desc_it": null, 
      "description": "Cut the rope to feed candy to Om Nom! A mysterious package has arrived, and the little monster inside has only one request? CANDY! Collect gold stars, discover hidden prizes and unlock exciting new levels in this addictively fun, award-winning, physics-based game!", 
      "featured": false, 
      "height": 576, 
      "hwcontrols": true, 
      "id": "40071", 
      "lastUpdate": "2015-09-01T09:44:42.240Z", 
      "orientation": "landscape", 
      "responsive": true, 
      "rkScore": 1000, 
      "thumbnailUrl": "https://az680633.vo.msecnd.net/thumbnail/40071/250/40071.png", 
      "thumbnailUrl100": "https://az680633.vo.msecnd.net/thumbnail/40071/100/40071.png", 
      "title": "Cut The Rope", 
      "touch": true, 
      "url": "http://games.gamepix.com/play/40071?sid=40161", 
      "width": 1024
    }, 
    {
      "author": "ZeptoLab", 
      "categories": [
        "Adventure", 
        "Classics", 
        "Puzzles"
      ], 
      "category": "Adventure", 
      "creation": "2015-05-19T12:09:42.672Z", 
      "desc_de": null, 
      "desc_en": null, 
      "desc_es": null, 
      "desc_fr": null, 
      "desc_it": null, 
      "description": "Join Om Nom as he travels back in time to feed his ancestors with candy. Cut the Rope: Time Travel is a completely new adventure filled with time-traveling, candy-crunching, physics-based action!", 
      "featured": true, 
      "height": 576, 
      "hwcontrols": true, 
      "id": "40072", 
      "lastUpdate": "2015-09-01T09:44:10.256Z", 
      "orientation": "landscape", 
      "responsive": true, 
      "rkScore": 999, 
      "thumbnailUrl": "https://az680633.vo.msecnd.net/thumbnail/40072/250/40072.png", 
      "thumbnailUrl100": "https://az680633.vo.msecnd.net/thumbnail/40072/100/40072.png", 
      "title": "Cut The Rope: Time Travel", 
      "touch": true, 
      "url": "http://games.gamepix.com/play/40072?sid=40161", 
      "width": 1024
    }
}

Любая помощь будет принята с благодарностью

Теги:

1 ответ

3
Лучший ответ

Вы можете использовать либо инъекцию прямой зависимости, либо именованную инъекцию зависимостей (с массивом).

Я бы рекомендовал именованный синтаксис как минимизатор, такой как uglify будет сжимать имена переменных. И вы получите синтаксические ошибки, поскольку он переименовывает аргументы как a, b и т.д. С помощью массива вы называете объект для инъекции, а затем (последний параметр, функцию), который вы используете, поэтому угловые все еще будут знать, какой объект вы хотите после сжатие переменных.

Проверьте синтаксис инъекции:

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

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

     }
     init();
   }
 ]);
  • 0
    Это сработало. Не могли бы вы объяснить, почему $ scope должен быть внутри функции?
  • 1
    @interneteur, я обновил свой ответ. Надеюсь, это поможет!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню