简体   繁体   English

如何获取json数据到离子数组?

[英]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. 我需要将json数据获取到array。以下是示例json数据。

{"state":"yes"}

from the above json data, I need to store only “state” values in array. 从上面的json数据中,我只需要在数组中存储“状态”值。 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: 阅读有关Observable对象的信息,通常具有以下结构:

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

Inside {} of your response function put all your implementation, in your case the if else structure are outside. 在您的响应函数的{}内放置所有实现,在这种情况下,if else结构不在外部。

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. 这里的问题是Observable是angular的对象,它是PROMISES的“升级”,因此是异步函数,在这种情况下,您使用的是http函数,因此应用程序向服务器发送请求,并且订阅将触发直到http响应,但其余代码仍会执行,因此请咨询。

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

are undefined because the http take some milliseconds response after that if, 之所以未定义,是因为http在此之后需要几毫秒的响应,

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. 阅读有关Java的Promise和Angular的Observables的更多信息。

I hope I've helped :) 我希望我有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM