Pass more than one parameter in a request in Angular for Webapi

Asked

Viewed 745 times

2

This is the web api:

[Route("{pagina:int}/{tamanhoPagina:int}")]
        [HttpGet]
        public IHttpActionResult UsuarioPaginado(int pagina = 1, int tamanhoPagina=10)
        {

            var _aluno = iAluno.Listar()
                        .Where(x => x.Nome != string.Empty)
                        .OrderBy(y => y.Nome).Skip(tamanhoPagina * (pagina - 1)).Take(tamanhoPagina);
            return Ok(_aluno);
        }

How to make my Angular application know when it’s page 2 or page 3 or 4 and so on?

Below is the form and the user needs to navigate to the Next or Previous: inserir a descrição da imagem aqui

The class below is the Service where I request the Web Api:

@Injectable({
  providedIn: 'root'
})
export class UsuarioService {

  constructor(private http: HttpClient) { }

    getListaUsuarios(): Observable<Usuario[]> {
      const url = `${environment.apiUrl}`;
      return this.http.get<Usuario[]>(url);
    }

    getListaAlunoPaginado(pagina: number, tamanhoPagina: number): Observable<Usuario[]> {
      const url = `${environment.apiUrl}/${pagina}/${tamanhoPagina}`;
      return this.http.get<Usuario[]>(url)
    }
}

And this is the class of the Component:
Obs.: in the code snippet where this.pagina = 1 the value is fixed and cannot, it has to be a dynamic value as the user clicks on next and there is my question: How to implement this dynamic value ?

export class ListarUsuarioComponent implements OnInit {
  public usuarios: Usuario[];
  public pagina: number;
  public tamanhoPagina: number;

  constructor(private usuarioService: UsuarioService) { }

  ngOnInit() {
    this.getListaAlunoPaginado(1,10);
  }

  getListaAlunoPaginado(pagina: number, tamanhoPagina: number) {
    this.usuarioService.getListaAlunoPaginado(pagina, tamanhoPagina)
      .subscribe((dados: Usuario[]) => {
        this.usuarios = dados,
        this.pagina = 1,                  <<--Aqui o valor está fixo, mas tem que ser um valor dinâmico conforme o usuário vai Clicando em Próximo.
        this.tamanhoPagina = 10;
      }, () => { 'Erro'; });
  }

}

2 answers

1

You can create a formData and pass it all to api, like this:

    getListaUsuariosPaginado(): Observable<Usuario[]> {
      const formData = new FormData();   
      formData.append('pagina', pagina);  
      formData.append('tamanho_pagina', tamanhoPagina);

      const url = `${environment.apiUrl}/`;
      return this.http.get<Usuario[]>(url, formData);
    }

Inside the append the first parameter is the name you will give, and the second is the data you want to send.

After that just pass the entire formData in the request and then capture the data in the api.

Only capture the data in the resquest api

$pagina = $request['pagina'];
$tamanhoPagina = $request['tamanho_pagina'];
  • The problem with this technique is that it wouldn’t follow the route, it could be a problem. or else it would have to change the route!

  • Thank you @Paulo Felipe Martins for your solution, but my question is not how send data and how to know when is page 2 or page 3, because I need to make a 10 in 10 records pagination, however I am seeing that my doubt was not so clear so I will edit my post and add more information to be clearer.

1


Look, if what you want is just to put the page numbers and set amount by it, there is a very simple option to do this, which is the Angular Datatables, do on the arm, you will spend a lot of time researching and it is a little complex to do, I did, but if I was to explain, it would have to be step by step and it’s gonna get really big, so.

Use the Angular Datatables https://l-lin.github.io/angular-datatables/#/basic/with-options in this link has explaining how to work, it has several functionalities, as well as paginate, dynamic search, quantity of items per page and etc.

The pagination part is more like this:

inserir a descrição da imagem aqui

And you don’t need to type lines and lines to page your data on the arm, it solves everything for you.

Basically you will install it in your project; Within your class you will import it: import { Datatabledirective } from 'angular-datatables';

It will create a property more or less like this:

public dtOptions: DataTables.Settings = {};

And set it up inside your ngInit, plus the less so:

  this.dtOptions = {
    pagingType: 'full_numbers',
    pageLength: 5,
    jQueryUI: true,
    language: <any>dtLanguage,
    autoWidth: false,
  };

In HTML you call these parameters in the table:

<table datatable [dtOptions]="dtOptions" class="row-border hover">

This is a pattern that I use. But the link above contains all the documentation of it. I believe this solves your question.

Here is also a link showing more background how to configure: https://stackoverflow.com/questions/51363693/using-full-featured-datatables-plugin-with-angular-6

  • Good morning! @Paulo Felipe Martins Thanks! This is what I need!

Browser other questions tagged

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