How to read the result of a JSON array using Ionic 3?

Asked

Viewed 841 times

0

I’m doing a GET for login, but I need to get the user ID for the session as well:

submit(){
    var link = 'http://localhost:1337/usuario?email='+ this.usuario.email  + '&senha='+ this.usuario.senha;
    var data = JSON.stringify({ email: this.usuario.email, senha: this.usuario.senha});

      this.http.get(link)
      .subscribe(data => {
        this.data.response = data._body;
       if(this.data.response != "[]"){
         console.log(this.data.response);

        // tinha que pegar o ID do usuário.... :/
         sessionStorage.setItem("usuarioEmail", this.usuario.email);
         sessionStorage.setItem("flagLogado", "sim");
         this.navCtrl.setRoot(WellFitPage, {}, {animate: true, direction: "forward"});
        }else{
          let alert = this.alertCtrl.create({
            title: 'Usuário Não encontrado!',
            subTitle: 'Verifique se digitou seu e-mail e senha corretamente.',
            buttons: ['OK']
          });
          alert.present();
       }
    })
  }

Man:

console.log(this.data.response);

Print this result in the Console:

[
  {
    "nome": "Ramos",
    "email": "[email protected]",
    "celular": "34996320391",
    "telefone": null,
    "data_nascimento": null,
    "altura": null,
    "peso": null,
    "gordura": null,
    "vo2": null,
    "senha": "teste",
    "cmkey": null,
    "id": 4,
    "createdAt": "2018-03-28T18:08:22.000Z",
    "updatedAt": "2018-03-28T18:08:22.000Z"
  }
]

How to get the id?

1 answer

1


Your local variable this.data.response is a array, therefore it is necessary to access its first position and then use dot Notation to access the desired property.

const response = [
  {
    "nome": "Ramos",
    "email": "[email protected]",
    "celular": "34996320391",
    "telefone": null,
    "data_nascimento": null,
    "altura": null,
    "peso": null,
    "gordura": null,
    "vo2": null,
    "senha": "teste",
    "cmkey": null,
    "id": 4,
    "createdAt": "2018-03-28T18:08:22.000Z",
    "updatedAt": "2018-03-28T18:08:22.000Z"
  }
];

console.log(response[0].id);

  • I am trying console.log('The user ID is: '+ this.data.Response[0].id); but it is Undefined

  • 1

    @Ramos and if you do http.get(link).map(response => response.json()).subscribe(data => { this.data.response = data; console.log(this.data.response[0.id]); });?

  • The problem was that it was a large string, which I solved by making a JSON.parse(this.data.Response); and applying its answer. And it worked. Thanks @mercador. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.