简体   繁体   中英

How to create a conditional based on a response object, for which the Key values are dependent and avoiding object.key() is Undefined

I'm subscribing to a method in Angular using typescript, which is a simple post Call that returns an entire HTTP Response. I'm wanting to create a simple conditional that checks to see if a certain key exists in the HTTP response. The conditional will work with an object that contains the key, but for an object that doesn't contain the key it throws an undefined.

Is there a way to omit the error or exception thrown and to proceed to the else portion

The keys of the object body are added if the user includes a number, without that it doesn't exist with the PhoneNumber key value

what I've tried / flipped the if and else

  • != undefined (vice versa)
  • == null (vice versa)
this.postMyName(userInfo).subscribe(
   (result:Response) => {
    if (result['body']['user'].hasOwnProperty(['PhoneNumber'])) {
        console.log("User has included a phoneNumber");
     } else {
           console.log("User has Not included a phoneNumber");
     }

    },error ...)

You can also try this solution maybe it will work

this.postMyName(userInfo).subscribe(
   (result:Response) => {
    if ('PhoneNumber' in result['body']['user'])) {
        console.log("User has included a phoneNumber");
     } else {
           console.log("User has Not included a phoneNumber");
     }

    },error ...)

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