未捕获的类型错误:不能调用方法'push'——Angularjs

Uncaught TypeError: Cannot call method 'push' of undefined - Angularjs

本文关键字:方法 push Angularjs 调用 不能 类型 错误      更新时间:2023-09-26

有人可以看看这个代码,并帮助找出为什么我一直得到这个错误。我是angularjs的新手(尤其是服务/工厂函数的使用)。当函数和局部变量在控制器(而不是$service)中定义为$scope变量时,它工作得很好,但是因为这个函数返回的数据是多个其他控制器所需要的,所以我想减少代码冗余。

 app.service('SupportService', function()
{
    var locations = []; //local variable to which other elements should be added

 //function to get data and update the local variable (this.locations)
 this.setLocations = function()
    {
        var temp_location = {};
        $.ajax
        ({
            type: 'get',
            url: 'myurl',
            success: function(response)
            {
                for(var i = 0; i < response.length; i++)
                {
                    temp_location =
                    {
                        id: response[i].id,
                        name: response[i].name
                    };
                    locations.push(temp_location);  //this is where the error is
                }
            },
            error: function(response)
            {
            }
        });
    }

从服务中访问位置变量的附加函数是

  this.getLocations = function()
    {
        return locations;
    }

我用来绑定数据的控制器如下

   app.controller('RSVPController', function($scope,SupportService,AuthService)
{
    $scope.init = function()
    {
        SupportService.setLocations();
    }
    $scope.locations = SupportService.getLocations();
});

,在视图中,我调用了这个控制器的init函数,并将值附加到select中,如下所示

<select ng-model="location" ng-options="item.name for item in locations track by item.id" required></select>

谢谢。

当你使用'this'时,你必须小心,因为在不同的作用域中,它可能指向不同的对象,你可以通过简单地删除this在闭包中放置位置。Service是单例的,它会记住的。

 app.service('SupportService', function()
{
   this.locations = []; //local variable to which other elements should be added
   var self = this;
    enter code here
 //function to get data and update the local variable (this.locations)
 this.setLocations = function()
    {
        var temp_location = {};
        $.ajax
        ({
            type: 'get',
            url: 'myurl',
            success: function(response)
            {
                for(var i = 0; i < response.length; i++)
                {
                    temp_location =
                    {
                        id: response[i].id,
                        name: response[i].name
                    };
                    self.locations.push(temp_location);  //this is where the error is
                }
            },
            error: function(response)
            {
            }
        });
    }
相关文章: