How do I search for Angular 8 id?

Asked

Viewed 151 times

0

Brought information from api by id, but I put it right into ngOnInit within the method the number of the id. I wanted to know how to search for these products in the input when pressing the button?

I have the service that brings the products by API id

listarProdutos(id: number):Promise<IResponse<any>>{
return this.http.get<IResponse<any>>(`mercado/produto/${id}`).toPromise();
}

And the Component you are receiving is as follows:

public produtos: ProdutosModel = [];

ngOnInit(): void{
this.listarProdutos(1);
}

contrutor(private produtoService: ProdutoService){}

listarProdutos(id){
this.produtoService.listarProdutos(id).then(response => {
this.produtos = response.data;
});}

And HTML is like this:

<input type="text"> <button (click)="buscar">Buscar</button>

<table *ngFor="let produtos of produtos">
<tr>
<td>id</td>
<td>nome</td>
<td>data vencimento</td>
</tr>
<tr>
<td>{{produtos.id}}</td>
    <td>{{produtos.nome}}</td>
    <td>{{produtos.dataVencimento}}</td>
</tr>

I also have the model

export class ProdutosModel{
id: number;
nome: string;
dataVencimento: string
}

1 answer

0


It is very simple this, indeed it has several ways of doing, one of them is passing a variable template in the input and pass the value that is entered in the function parameter fetch():

<input type="text" #ID> <button (click)="buscar(ID)">Buscar</button>

In function fetch() vc executes the service according to the value received in the parameter:

public produtos: ProdutosModel[] = [];

ngOnInit(): void{}

construtor(private produtoService: ProdutoService){}

listarProdutos(id){
  this.produtoService.listarProdutos(id).then(response => {
    this.produtos = response.data;
  });
}

buscar(id: any){
  let _id = id.value;

  this.listarProdutos(_id);
}

OBS: The most correct parameter in the listProducts() method in the service is to be of the type string and not number, pq will take this parameter from a input, and every value of an input type is string.

Browser other questions tagged

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