Home > Net >  how to access a property of an interface in angular
how to access a property of an interface in angular

Time:08-06

I have this interface, I would like to access its ID property, from another component

export interface IItem {
 id: number;
 status: any;
peso: number;
medidas: any;
quantidade: number;
tabela: {
itemTabela_id: number;
item_id: number;
vPromo: number;
vPromoData: any;
vVenda: number;
};
estoque: {
estAtual: number;
item_id: number;
};
item_linkWeb: any;
descricao: string;
fotos: Array<string>;

}

how could I access her object ID for example?

test(){
console.log(item: IItem)
}

in this part of the code it shows the output of the normal item, item by item, the function updateQuantidade returns the normal item.id in the console

<tr *ngFor="let item of cartS.cart.item; let i = index">
            <td>
              <figure >
                <div  *ngIf="item.fotos">
                  <img src="https://esal.api.alleshub.com.br/images/erp_{{layout}}/item/{{
                      item.fotos[0]
                    }}.jpg"  alt="{{item.item_linkWeb.linkWeb.titulo}}" />
                </div>
                <figcaption >
                  <h6  style="max-width: 350px;">
                    {{ item.item_linkWeb.linkWeb.titulo }}
                  </h6>
                  <!-- <dl >
                    <dt>Variação:</dt>
                    <dd>G</dd>
                  </dl>
                  <dl >
                    <dt>Cor:</dt>
                    <dd>Vermelha</dd>
                  </dl> -->
                </figcaption>
              </figure>
            </td>
            <td style="padding-top: 1.2em">

              <div>
                    <input  [(ngModel)]="quantidade" (ngModelChange)="updateQuantidade(item)" type="number" name="quantity" min="1" max="{{this.item.estoque.estAtual}}"/>
               </div>
            </td>
            <td>
              <div >
                <var >{{
                  (item.tabela.vPromo || item.tabela.vVenda) *
                  item.quantidade | currency: "BRL"
                  }}</var>
                <small >({{
                  item.tabela.vPromo || item.tabela.vVenda
                  | currency: "BRL"
                  }}
                  cada)</small>
              </div>
            </td>
            <td >
              <!-- <a data-original-title="Salvar na lista de desejos" title="" href="" 
                data-toggle="tooltip">
                <i ></i></a> -->
              &nbsp;
              <button type="button"  data-toggle="modal"
                data-target="#modalConfirmDelete" (click)="excluirItemCart(i)">
                <i ></i>
              </button>
            </td>
          </tr>

The updatequantidade

updateQuantidade( item: IItem) {
console.log(item)
console.log(item.id)
if (this.quantidade > item.estoque.estAtual) {
  this.quantidade = item.estoque.estAtual;
  this.modalS.createModal(MdAlertComponent, { title: 'Estoque insuficiente', message: `Só há ${item.estoque.estAtual} unidade(s) deste item em estoque` });
}
const index = this.cartS.cart.item.indexOf(item);
this.cartS.cart.item[index].quantidade = this.quantidade;
this.cartS.updateItem(item);
}

but in this other function that doesn't have the ngFor="let item of cartS.cart.item; let i = index">, it always returns undefined

            <form>
          <div >
            <label>Calcular o Frete</label>
            <div >
              <input [(ngModel)]="cep" [ngModelOptions]="{standalone: true}" type="text" 
                name="" placeholder="Digite o CEP" />
              <span >
                <button (click)="getFreteByCep(cep,item)" [ngClass]="{'d-none': (loadingCep)}"
                  >Verificar</button>
                <div  [ngClass]="{'d-none': (!loadingCep)}"
                  style="width: 2rem; height: 2rem;margin-left:5px;margin-top: 2px;"></div>
              </span>
            </div>
            <span  (click)="openMdNaoSeiCep()"><u>Não sei o CEP</u></span>
          </div>
          <div >
            <label>Tem um cupom?</label>
            <span *ngIf="cupomAplicado"  (click)="retirarCupom()">Retirar cupom</span>
            <div >
              <input style="height: 40px"
                type="text"
                
                placeholder="Código do cupom"
                [(ngModel)]="codCupom"
                [ngModelOptions]="{standalone: true}"
                [disabled]="cupomAplicado"
              />
                <div >
                    <span  [ngClass]="{'bg-success': (!loadingCupom)}" style="width: 62px; height: 40px;">
                        <a (click)="aplicarCupom()" [ngClass]="{'d-none': (loadingCupom)}">Aplicar</a>
                        <div  [ngClass]="{'d-none': (!loadingCupom)}" style="width: 2rem; height: 2rem;"></div>
                    </span>
                </div>
            </div>
          </div>
        </form>
 getFreteByCep(cep,item: IItem   ) {
console.log(item)
console.log(item.id)}

CodePudding user response:

An interface does not hold values by itself. Rather it defines the type of the reference that points to the actual value.

You could do something like:

@Component({...})
export class MyComponent {
    private item: IItem;

    public test(): void {
        console.log(this.item);
        console.log(this.item?.status);
    }
}

But unless you actually set a value to your variable, all you are going to see is undefined.

CodePudding user response:

Now, your item has the shape of the interface called IItem. To access the properties you need just to do something like:

item?.id
item?.tabela?.item_id

The ? mark is called the optional chaining operator and it is used to prevent runtime errors against undefined properties.

  • Related