简体   繁体   中英

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. TypeError: Cannot read property 'push' of null

NOTICE! This only happens when inputting the FIRST value into the object and after that it works fine.

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.

in your controller you can initialize the variable yourself, don't let it be 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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