0

I want to make a method that only makes another request when the before request return StatusCode 200. I'm using angular 15.

My home.component.ts look like this and I want to todasGuias() only make another request at a time.

    todasGuias() {
    this.page= 1;
    while (this.page <= this.listaGuias.TotalPages) {
      this.homeService.getGuias( this.year, this.month, this.glosadas, this.page)
      .subscribe((data)=>{
        this.listaGuias = data.Dados[0]
        console.log(this.listaGuias.ResultList);
      })
      this.page++;
    }
  }

and my home.service.ts look like this:

 public getGuias( year: any, month: any, glosadas: any, page:any): Observable<any> {
    const token = this.token.retornaToken();
    const headers = new HttpHeaders({ Authorization: `Bearer ${token}` });

    return this.http.get(API/list?TpoRelatorio=1
    &SomenteGlosadas=${glosadas}
    &Ano=${year}
    &Mes=${month}
    &Page=${page}
    &Count=0`,{ headers }
    )
  }

any help?

nate-kumar
  • 1,675
  • 2
  • 8
  • 15
Hugo vilar
  • 101
  • 6

1 Answers1

1

You want to use the rxjs operator switchMap to achieve this:

todasGuias() {
    range(1, this.listaGuias.TotalPages).pipe(
       switchMap(page => this.homeService.getGuias( this.year, this.month, this.glosadas, page))
    ).subscribe((data)=>{
        this.listaGuias = data.Dados[0]
        console.log(this.listaGuias.ResultList);
      })
    }
  }

This assumes you know the total number of pages beforehand. range generates an Observable with every number from 1 to TotalPages. switchMap then maps each number to an Observable executing the http request. As switchMap only retains one subscription internally all the requests are made sequentially. If one request fails, the Observable will also fail.

Garuno
  • 1,935
  • 1
  • 9
  • 20
  • it didn't work, it makes the request just of the first page – Hugo vilar Dec 19 '22 at 10:35
  • Are you sure that `this.listaGuias.TotalPages` is set correctly while calling the function? This approach only works, if the `this.listaGuias.TotalPages` are known at the time the function is called. – Garuno Dec 19 '22 at 10:42
  • Yes I'm sure. example: if TotalPages is 3 it makes 3 requests of the first page – Hugo vilar Dec 19 '22 at 14:06
  • So I tested it again. It works for me. The only thing I can think of is that you wrote `this.page` instead of just `page` in the function parameters of `this.homeService.getGuias`. – Garuno Dec 19 '22 at 17:34