简体   繁体   English

TypeError:插入第一个值时无法读取null的属性“ push”

[英]TypeError: Cannot read property 'push' of null when inserting first value

So I have been trying to wrap my head around this for hours now and can't seem to figure it out, i've tried the different solutions that people have discussed here in Stackoverflow such as checking if there is an array and if not make one and what not, but I still get the error. 因此,我已经尝试了好几个小时了,似乎无法弄清楚。我尝试了人们在Stackoverflow中讨论过的各种解决方案,例如检查是否存在数组以及是否创建数组。一,什么也不是,但我仍然得到错误。 TypeError: Cannot read property 'push' of null TypeError:无法读取null的属性“ push”

NOTICE! 注意! This only happens when inputting the FIRST value into the object and after that it works fine. 仅在将FIRST值输入到对象中之后,此方法才能正常工作。

Here is the global variable 这是全局变量

$scope.globalTitleArray = $scope.globalTitleArray || [];

Here is my controller 这是我的控制器

$scope.addDefaultTitle = function () {
    if ($scope.assignment.title === ""){
            $flashMessage.error('Du måste fylla i titelfältet innan du lägger till en default title.')
    }else{
    if ($scope.assignment.innerCategory === null) {
        $flashMessage.error('För att lägga till en default title måste du först spara en inner category, samt när du skriver in din önskade default title ska area ej finnas med.', 'Error');
    }
       categoryService.addDefaultTitle($scope.assignment.innerCategory.id, $scope.assignment.title).then(function () {
            $flashMessage.success('The Default Title has been added.', 'Saved');

            var areaName = $scope.postalCodeName ? $scope.postalCodeName : $scope.assignment.subArea.short_name;
            return $scope.assignment.title = $scope.assignment.title + ', ' + areaName;
        });
        $scope.globalTitleArray.push($scope.assignment.title);
    }
};

$scope.globalTitleArray can't be a global variable as it's part of the controller's scope, so be careful what you do with it and how you use it. $ scope.globalTitleArray不能是全局变量,因为它是控制器范围的一部分,因此请小心使用它以及如何使用它。

in your controller you can initialize the variable yourself, don't let it be null : 在控制器中,您可以自己初始化变量,不要让它为null:

app.controller('someController', ['$scope', function ($scope) {

    $scope.globalTitleArray = [];

    other stuff and methods ....

}]);

if you want to use that variable outside of this controller which why I assume you mentioned global then you do that by using a service and injecting it into whatever controller needs to use it.A service is basically a singleton, meaning it is only instantiated once and effectively it gives you state. 如果您想在该控制器之外使用该变量(为什么我假设您提到了全局变量),则可以通过使用服务并将其注入需要使用它的任何控制器中来实现。服务基本上是单例,这意味着它仅被实例化一次有效地给您状态。

If you have this array in a service, just initialize it the same way as an empty array and don't assign null to it, then you can push to it anytime you need to. 如果您在服务中拥有此数组,只需以与空数组相同的方式对其进行初始化,并且不为其分配null,则可以在需要时随时将其推入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM