简体   繁体   中英

How to fix Cannot read property hasOwnProperty of undefined

How to fix Cannot read property 'hasOwnProperty' of undefined?

Using Angular.JS 1.3

Assigning response data in $rootScope.settings in parentConroller .

so the rootScope will be like this

    $rootScope.settings = api.data;

//sample
    $rootScope.settings:{
        "lastLogin":"2005-01-01",
        "isStudent": true,
        "assignedCourse": "['JAVA + DS']"
    }

And accessing the $rootScope data in anotherController.JS. But here I don't want my array inside string, so to remove double quotes, I tried below ways

Attempt 1:

 if($rootScope.settings.hasOwnProperty('assignedCourse')) {
        $rootScope.settings.assignedCourse = ['JAVA + DS']
    }

Attempt 2:

$rootScope.settings.assignedCourse = JSON.parse(rootScope.settings.assignedCourse.replace(/'/g, '"'));

// giving me Error: Unexpected token ' in JSON at position 1

Attempt 1 is working in the application, but its getting failed when i run karma debugger which is showing TypeError: Cannot read property 'hasOwnProperty' of undefined

Literally don't know how to fix this issue. Struggling to fix more than a days

I've already gone through few SO's related to my issues. but don't get any better solutions

Side Note: currently using only plain old JavaScript, not es6 or updated version.

For starters, you may want to be using angular.isDefined($rootScope.settings.assignedCourse) instead of hasOwnProperty as it is likely syntactically closer to what you are testing for (defined value instead of property ownership)

Regarding attempt 1 failing in the test, settings is undefined. You may need to re-examine your test bed and ensure your scope is being initialized as you expect.

I recreated your attempt 2 successfully, I suspect something else is going on here and may be resulting from another line.

示例代码

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