Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未定义angularjs服务中的方法_Javascript_Angularjs_Dependency Injection_Angular Services - Fatal编程技术网

Javascript 未定义angularjs服务中的方法

Javascript 未定义angularjs服务中的方法,javascript,angularjs,dependency-injection,angular-services,Javascript,Angularjs,Dependency Injection,Angular Services,我正在浏览ng时事通讯中的2048游戏教程,但我的gridservice方法还没有定义 下面是注入网格模块及其网格服务的代码模块 angular.module('Game', ['Grid']) .service('GameManager', ['GridService', function(GridService) { // create a new game this.newGame = function() { GridServ

我正在浏览ng时事通讯中的2048游戏教程,但我的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.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;
    });
角度模块('网格',[]) /** *GridService处理董事会的所有条件 */ .service('GridService',['TileModel',函数(TileModel){ 返回{ buildEmptyGameBoard:buildEmptyGameBoard } this.startingTileNumber=2; //网格阵列充当电路板并保持静态 this.grid=[]; //瓦片阵列作用于板上的碎片,并将是动态的 this.tiles=[]; this.tiles.push(新的TileModel({x:1,y:1},2)); this.tiles.push(新的TileModel({x:1,y:2},2)); //董事会的规模 这个尺寸=4; //this.buildEmptyGameBoard=函数(){ 函数buildEmptyGameBoard(){ var self=这个; //初始化网格 对于(var x=0;x 当前我得到的结果是:错误:this.forEach不是一个函数

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


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

这里有两个错误-一个是即时错误,另一个是在修复第一个错误后立即发现的错误

  • “this”并不总是Javascript中所期望的。调用函数不会改变上下文(您可以使用诸如call/apply/bind之类的方法),因此请注意您的“this”指针。使用标准JS技巧将获得更好的结果:

    var self = this;
    
    然后在任何地方使用“self”而不是“this”

  • this.forEach不存在,因为您在服务本身(this)或调用方的上下文(取决于您调用服务的方式)上调用它。您的意思是
    this.tiles.forEach()

  • 您调用了
    GridService.buildStartingPosition();
    ,但尚未定义它。一旦修复了forEach,这将在此处引发异常

  • 您有一个早期返回语句。在函数的开头:

    return {
        buildEmptyGameBoard: buildEmptyGameBoard
    }
    
    表示永远不会执行以下语句:

    this.startingTileNumber = 2;
    ...etc...
    
    Javascript在第一个过程中运行声明(即
    buildEmptyGameBoard
    被声明并将被定义),但不运行语句(即
    this.forEach=function(cb){}
    将在第二个过程中等待运行)。但在第二个过程中,将立即执行返回,并且不会运行任何其他语句

    因此**将
    return
    放在函数的末尾

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

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

  • 非常感谢,这对理解它的流程非常有帮助。我最终使用了var self=this work around,因此我不必将所有方法附加到return语句中。非常感谢这里的指针,我忘记了self=this work around。这解决了我的问题