0

I'm Working on search form were i need to check whether city is empty or not. If it is empty then assign Bangalore to it other show the selected city. Here is my If condition

if(this.locations[0].city!="")
{
   var Dynamic = this.locations[0].city;
}
else
{
   Dynamic = "Bangalore";
}

But getting

Runtime Error. cannot read property '0' of undefined.

I am new to Ionic 2.

3 Answers 3

1

modify the IF condition like the below

 if(this.location!=undefined && this.location.length!=0 && this.locations[0].city!="")
    {
       var Dynamic = this.locations[0].city;
    }
    else
    {
       Dynamic = "Bangalore";
    }
Sign up to request clarification or add additional context in comments.

Comments

1

I might do this

var Dynamic = "Bangalore";
' first to are verifying they are defined
if(this.locations && this.locations[0] && this.locations[0].city && this.locations[0].city.length > 0)
{
  Dynamic = this.locations[0].city;
}

1 Comment

I think this will fail if this.locations[0] is undefined.
0

I suggest you create a function called checkNested for checking the validity of a nested object and use it throughout your app. You can put that in a service.

Also, I think you should define Dynamic outside of the if statement for scoping reasons.

var Dynamic = "Bangalore";
if(this.locations &&  // Checking if this.locations is valid before indexing it
   this.checkNested(this.locations[0], "city") && 
   this.locations[0].city !="" ){
   Dynamic = this.locations[0].city;
}

checkNested function is defined here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.