javascript - AngularJS 服务中的方法未定义

标签 javascript angularjs dependency-injection angular-services

我正在阅读 ng-newsletter 的 2048 游戏教程,但我的网格服务方法尚未定义。

这里是注入(inject)Grid模块及其GridService的代码模块

angular.module('Game', ['Grid'])
  .service('GameManager', ['GridService', function(GridService) {

        // create a new game
        this.newGame = function() {
            GridService.buildEmptyGameBoard();
            GridService.buildStartingPosition();
            this.reinit();
        };
  }]);

这是我的 Grid 模块和 Gridserivce 以及未定义的 Angular 引用方法:

    angular.module('Grid', [])

            /**
             * GridService handles all the conditions of the board
             */
            .service('GridService', ['TileModel', function(TileModel) {

                return {
                    buildEmptyGameBoard: buildEmptyGameBoard
                }

                this.startingTileNumber = 2;



                // grid array acts the as the board and remains static
                this.grid = [];

                // tiles array acts the pieces on the board and will be dynamic
                this.tiles = [];
                this.tiles.push(new TileModel({x: 1, y: 1}, 2));
                this.tiles.push(new TileModel({x: 1, y: 2}, 2));

                // Size of the board
                this.size = 4;


                //this.buildEmptyGameBoard = function() {
                function buildEmptyGameBoard() {
                    var self = this;

                    // Initialize our grid
                    for(var x = 0; x < this.size * this.size; x++) {
                        this.grid[x] = null;
                    }

                    // Initialize our tile array 
                    // with a bunch of null objects
                    this.forEach(function(x,y) {
                        self.setCellAt({x:x, y:y}, null);
                    });

                }


        // Run a method for each element in the tiles array
                this.forEach = function(cb) {
                    var totalSize = this.size * this.size;
                    for(var i = 0; i < totalSize; i++) {
                        var pos = this._positionToCoordinates(i);
                        cb(pos.x, pos.y, this.tiles[i]);
                    }
                };

    // Convert i to x,y
            // cell position from single dimensional array
            // converts to x and y coords for pos on game board
            this._positionToCoordinates = function(i) {
                var x = i % service.size;
                    y = (i - x) / service.size;
                return {
                    x: x,
                    y: y
                };
            };


}])

    /**
     * TileModel Factory to define values for our tile directive css positions
     */
    .factory('TileModel', function() {
        var Tile = function(pos, val) {
            this.x = pos.x;
            this.y = pos.y;
            this.value = val || 2;
        };

        return Tile;
    });

当前我收到此消息:错误:this.forEach 不是函数

我已经能够解决这个应用程序中的一些其他错误。所有错误都与我的 gridService 中的方法未定义或不是函数有关。我的 GridService 似乎存在根本性错误或缺失,但我没有看到。

注意:这两个文件都被调用并在我的index.html 文件中正确加载

最佳答案

  1. 您有一份提前返回声明。在函数的开头:

    return {
        buildEmptyGameBoard: buildEmptyGameBoard
    }
    

    表示以下语句永远不会被执行:

    this.startingTileNumber = 2;
    ...etc...
    

    Javascript 在第一遍中运行声明(即 buildEmptyGameBoard 已声明并将被定义),但运行语句(即 this.forEach = function (cb) {} 将等待在第二遍运行)。但在第二遍时,立即执行返回,并且不执行任何其他操作。

    所以**将return放在函数的末尾。

  2. 服务不是 Controller ,它不是用 new 实例化的。您的服务返回一个具有 1 个方法的对象,buildEmptyGameBoardthis.forEach = function(cb) {} 会将 foreach 函数附加到某个未知对象,当然不是返回的对象。因此,将您的代码更改为:

    function buildEmptyGameBoard() { ... }
    function foreach(cb) { ... }
    ...etc...
    
    return {
        buildEmptyGameBoard: buildEmptyGameBoard,
        foreach: foreach,
        ...etc...
    };
    

关于javascript - AngularJS 服务中的方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25941009/

相关文章:

Javascript bootstrap,整个页面在模态中显示重复

javascript - 通过工作表脚本选择下拉项时发送电子邮件

dependency-injection - 具有开放通用接口(interface)的温莎类型工厂

c# - NuGet包库中的依赖注入(inject)

c# - ParameterOverride 在 System.Type 参数上失败

javascript - 将 jQuery ID 选择器与 CSS 结合使用

javascript - 使用 AngularUI 作为热键

javascript - RadListView : animate template selection change

javascript - 动态创建 JSON 对象 Angular

javascript - {{result}} 和 $scope.result 在 AngularJS 中如何关联?