JSON with array within IONIC 3

Asked

Viewed 345 times

-1

I would like to know how I recover the data coming from a Rest api, where I have an array within a Json.

Example Below:

[
  {
    "Presencas": [],
    "Turma": {
      "Alunos": [],
      "Voluntarios": [],
      "Id": 1,
      "Nome": "Futebol Pequenos",
      "IdadeMinima": 4,
      "IdadeMaxima": 10,
      "HorarioInicial": "08:00:00",
      "HorarioFinal": "09:00:00",
      "DiaSemana": "Sábado",
      "QuantidadeDeAlunos": 0
    },
    "Id": 5,
    "DataAula": "2019-01-05T00:00:00",
    "DataEnvio": "2019-01-30T21:38:42",
    "TurmaID": 1,
    "AlunosPresentes": 0
  }
]

I’m doing like this

this.rest.getAula().then((result: any[]) => {
    this.aulas = result;
    this.aulas.forEach(elemento => {
        console.log(elemento.Id);
    });
});

But the only returnees are these

"Id":5,
"DataAula":"2019-01-05T00:00:00",
"DataEnvio":"2019-01-30T21:38:42",
"TurmaID":1,
"AlunosPresentes":0

I need this information

{
  "Turma": {
    "Alunos": [],
    "Voluntarios": [],
    "Id": 1,
    "Nome": "Futebol Pequenos",
    "IdadeMinima": 4,
    "IdadeMaxima": 10,
    "HorarioInicial": "08:00:00",
    "HorarioFinal": "09:00:00",
    "DiaSemana": "Sábado",
    "QuantidadeDeAlunos": 0
  }
}

Can someone help me?

  • have tried elemento[0]['Turma'] ?

2 answers

0

If you are sure it will always be a value in the array or it will always get the first value:

const turma = result && result.length > 0 ? 
               dados[0].Turma :  // primeira turma no array
               null; // vazio se nao existir

console.log(turma);

If you want to filter the values and return a list of classes per id, you can use:

function encontrarTurmaPorId(id: string): any {
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
  if (!Array.isArray(dados)) {
    return []; // Nenhuma turma
  }


  // Filtra valores e retorna apenas turmas com ID específico
  // Recomendo trocar o "any" pela sua interface/tipo
  const turmas = dados.filter((items: Array<any>) => items.Turma.Id === id);

  return turmas;
}

console.log(encontrarTurmaPorId(1)); // retorna lista de turmas com id 1
  • this way did not work, I need to display this data on the screen Name": "Small Football", "Idademinima": 4, "Idademaxima": 10, "Horarioinitial": "08:00:00"

0

Eai man, next. If you want to get the data straight from the API, do so:

Creates a global variable like this:

http: Http;

Then capture the API data this way:

 var aula;
    this.http.get('link/para/sua/api').map(res => res.json()).subscribe(data => {
        aula = data;
        console.log(aula);
    });
  • there is no . json() method in the new Httpclientmodule

Browser other questions tagged

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