简体   繁体   中英

How to get json data to array in ionic?

I am new in ionic. I need to get json data to array.below is the sample json data.

{"state":"yes"}

from the above json data, I need to store only “state” values in array. Please suggest any solution. Yhank you.

login()
  {
    let hash = CryptoJS.SHA256(this.user_password).toString(CryptoJS.enc.Hex);
    let data:Observable<any>;
    data = this.http.get('mydomain/api/?loginUn='+this.user_name+'&password='+hash);
    data.subscribe(result=>
      {
        this.items = result;
      })
    if(this.items['state'] == "yes")
    {
      console.log("state yes");
    }
    else
    {
      console.log("else");
    }
  }

Here its my error

TypeError: Cannot read property 'state' of undefined

Read about the Observable objects, generally has the structure:

variable.subscribe(
    (response) => {},
    (error) => {}
);

Inside {} of your response function put all your implementation, in your case the if else structure are outside.

The issue here is that the Observable is object of angular that is an "upgrade" of PROMISES , so is an asynchronous function, in this case you are using a http function, so the app do the request to server, and subscribe will fire until the http response, but the rest of code still execute, so when you consult.

if(this.items['state'] == "yes")

are undefined because the http take some milliseconds response after that if,

so you need to do is:

data.subscribe(
 (result) => {
    this.items = result;

    if(result['state'] == "yes"){
      console.log("state yes");
    } else{
       console.log("else");
    }
  },
  (error)=> {
     //When subcribe, in this case http fail in something
  }
 );

Read more about of Promise on Javascript and Observables of Angular.

I hope I've helped :)

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