Handle HTTP Request with Item Array as response

Asked

Viewed 99 times

1

Whoa, all right, guys?

Maybe this question won’t help anyone, but I don’t know but what to do, you Stackoverflow guys are my hope.

Next, on the page I’m mounting, will show all the plans that an academy has with value, name, installments and etc...

This is the JSON:

{
    "Registros": 4,
    "Itens": [
        {
            "ItemOnlineID": "2",
            "ItemID": "51",
            "ItemNome": "CROSS FIT ECONOMICO",
            "ItemTipoID": "101",
            "ItemTipo": "MENSAL",
            "ItemRecorrencia": "1",
            "ItemMatriculaID": null,
            "ItemMatriculaDescricao": null,
            "ItemMatriculaValor": null,
            "ItemLink": "vendas.academiaweb.com.br/BrfitPampulha-949-2",
            "ItemValores": [
                {
                    "ItemValorID": "56",
                    "ItemValorQuantidade": "2",
                    "ItemValorPreco": "239.00",
                    "ItemValorLimiteParcelas": "1",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                },
                {
                    "ItemValorID": "57",
                    "ItemValorQuantidade": "3",
                    "ItemValorPreco": "259.00",
                    "ItemValorLimiteParcelas": "1",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                },
                {
                    "ItemValorID": "58",
                    "ItemValorQuantidade": "5",
                    "ItemValorPreco": "279.00",
                    "ItemValorLimiteParcelas": "1",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                }
            ]
        },
        {
            "ItemOnlineID": "4",
            "ItemID": "40",
            "ItemNome": "PILATES+AEROBICO",
            "ItemTipoID": "101",
            "ItemTipo": "MENSAL",
            "ItemRecorrencia": "0",
            "ItemMatriculaID": null,
            "ItemMatriculaDescricao": null,
            "ItemMatriculaValor": null,
            "ItemLink": "vendas.academiaweb.com.br/BrfitPampulha-949-4",
            "ItemValores": [
                {
                    "ItemValorID": "44",
                    "ItemValorQuantidade": "1",
                    "ItemValorPreco": "284.00",
                    "ItemValorLimiteParcelas": "1",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                },
                {
                    "ItemValorID": "45",
                    "ItemValorQuantidade": "2",
                    "ItemValorPreco": "310.00",
                    "ItemValorLimiteParcelas": "1",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                },
                {
                    "ItemValorID": "46",
                    "ItemValorQuantidade": "3",
                    "ItemValorPreco": "345.00",
                    "ItemValorLimiteParcelas": "1",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                }
            ]
        },
        {
            "ItemOnlineID": "1",
            "ItemID": "11",
            "ItemNome": "ARTES MARCIAIS",
            "ItemTipoID": "102",
            "ItemTipo": "PLANO",
            "ItemRecorrencia": "1",
            "ItemMatriculaID": "7",
            "ItemMatriculaDescricao": "TAXA DE ADESAO ARTES MARCIAIS",
            "ItemMatriculaValor": "35.00",
            "ItemLink": "vendas.academiaweb.com.br/BrfitPampulha-949-1",
            "ItemValores": [
                {
                    "ItemValorID": "36",
                    "ItemValorQuantidade": "6",
                    "ItemValorPreco": "840.00",
                    "ItemValorLimiteParcelas": "6",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                },
                {
                    "ItemValorID": "27",
                    "ItemValorQuantidade": "12",
                    "ItemValorPreco": "1500.00",
                    "ItemValorLimiteParcelas": "12",
                    "ItemValorDescontoID": "2",
                    "ItemValorDescontoDescricao": "CONVENIOS",
                    "ItemValorPrecoDesconto": "1200.000000000000000000000000000000"
                }
            ]
        },
        {
            "ItemOnlineID": "3",
            "ItemID": "10",
            "ItemNome": "PILATES 3X",
            "ItemTipoID": "102",
            "ItemTipo": "PLANO",
            "ItemRecorrencia": "1",
            "ItemMatriculaID": null,
            "ItemMatriculaDescricao": null,
            "ItemMatriculaValor": null,
            "ItemLink": "vendas.academiaweb.com.br/BrfitPampulha-949-3",
            "ItemValores": [
                {
                    "ItemValorID": "25",
                    "ItemValorQuantidade": "3",
                    "ItemValorPreco": "858.00",
                    "ItemValorLimiteParcelas": "3",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                },
                {
                    "ItemValorID": "26",
                    "ItemValorQuantidade": "6",
                    "ItemValorPreco": "1620.00",
                    "ItemValorLimiteParcelas": "6",
                    "ItemValorDescontoID": null,
                    "ItemValorDescontoDescricao": null,
                    "ItemValorPrecoDesconto": null
                }
            ]
        }
    ],
    "ErrMsg": ""
}

As you can see, Items is an array of objects that has 4 items, inside each one has another array of objects "Itemvalores".

What’s the problem, I need to show or hide things based on certain items within this Array as for example:

In item 1 ("Itemonlineid = 2") the plan has no discount ("Itemvalorprecodesconto = null") so I must display the ("Itemvalorpreco")

But if it has a discount, as in item 3 ("Itemonlineid = 1"), instead of ("Itemvalorpreco") I must display ("Itemvalorprecodiscount"), and I have no idea how to do that.

My code is like this:

planos.ts

export class Planos {
  itens: any[];
  planoNome: string;
  planoTipo: string;
  ItemValores = {
    planoQuantidade: '',
    planoPreco: '',
    planoLimiteParcelas: '',
    planoPrecoDesconto: '',
  };
}
plano.service.ts

export class PlanoService {

  constructor(private http: HttpClient) { }

  async receberPlanos(planos) {
    await this.http
      .get(url)
      .toPromise()
      .then(res => {
        planos.itens = res.Itens;
        // ***Para acessar cada um dos 4 items dentro do Array de objetos "Itens"***
        for (const e in planos.itens) {
          planos.planoNome = res.Itens[e].ItemNome;
          planos.planoTipo = res.Itens[e].ItemTipo;
        // ***Para acessar cada um dos items dentro do Array de objetos "ItemValores" dentro de "Itens"***
          for (const i in planos.itens[e].ItemValores) {
            planos.ItemValores.planoQuantidade = res.Itens[e].ItemValores[i].ItemValorQuantidade;
            planos.ItemValores.planoPreco = res.Itens[e].ItemValores[i].ItemValorPreco;
            planos.ItemValores.planoLimiteParcelas = res.Itens[e].ItemValores[i].ItemValorLimiteParcelas;
            planos.ItemValores.planoPrecoDesconto = res.Itens[e].ItemValores[i].ItemValorPrecoDesconto;

          }
        }
      });
  }
}

But since it is an Array of objects, the item "planName" for example, will actually receive each of the names of the planes, but will remain with the last.

So how do these checks? I’m completely lost.

  • You can’t handle this in your Komponent and use an if to check each object?

1 answer

1


You can make two loops, one to list the plan name and one to list the packages. To treat the price display with or without discount just use a very simple logic with the *ngIf (do not forget to import the CommonModule to use it). See for example the template below:

<div *ngFor="let item of meusDados">
  {{item.ItemNome}}
  <div *ngFor="let a of item.ItemValores">
    <span *ngIf="a.ItemValorPrecoDesconto">
      {{a.ItemValorPrecoDesconto}}
    </span>
    <span *ngIf="!a.ItemValorPrecoDesconto">
      {{a.ItemValorPreco}}
    </span>
  </div>
  <hr />
</div>

And in the TS code of your component:

import { Component, OnInit } from '@angular/core';
import { DadosService } from './dados.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  meusDados: Array<any> = [];

  constructor(private dadosService: DadosService) {

  }

  ngOnInit() {
    // Retorna exatamente o JSON que você postou
    this.dadosService.getDados()
      .subscribe(dados => {
        this.meusDados = dados.Itens;
      });
  }
}

In the service you do not need to map "in hand" the returned data, just create an interface(s) that represents your data model and use it in the `get. Code of service I created to simulate your problem:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class DadosService {
  constructor(private http: HttpClient) {

  }

  getDados() {
    return this.http
      // Ao invés do "any" crie uma interface para mapear seu modelo de dados
      .get<any>('https://5e163b0422b5c600140cf959.mockapi.io/aaa');
  }
} 
  • But I used an interface, I used this site: http://www.jsontots.com and pasted that JSON there.

Browser other questions tagged

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