简体   繁体   中英

Undefined is not an object - Angular $rootScope.user.userMessage

I keep getting an error of

Error: undefined is not an object (evaluating '$rootScope.user.userMessage')

with this code:

if (typeof($rootScope.user.userMessage) === null) {

but if I do have something in $rootScope.user.userMessage it doesn't crash. How can I perform a check to see if this is undefined or null so that the thing doesn't break?

other things i've tried include:

if (typeof($rootScope.user.userMessage) === undefined) {
if ($rootScope.user.userMessage === undefined) {
if($rootScope.user && $rootScope.user.userMessage){
    ...
}

Typeof is not a function. You have to use it this way

if (typeof $rootScope.user.userMessage === "undefined") {

You can make the expression null safe

if ($rootScope !=null && $rootScope.user!=null &&  $rootScope.user.userMessage != null) {
  ...
}

if you are checking for only undefined you can use

angular.isDefined($rootScope.user.userMessage);

or

angular.isUndefined($rootScope.user.userMessage);

but the beat practices is to use

if($rootScope.user && $rootScope.user.userMessage){
    ...
}

it will check both null,undefined or empty within only one condition.

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