简体   繁体   English

方法以角度返回 HttpStatusCode

[英]Method returns HttpStatusCode in angular

I want to make a method that only makes another request when the before request return StatusCode 200. I'm using angular 15.我想制作一个仅在前一个请求返回 StatusCode 200 时发出另一个请求的方法。我使用的是 angular 15。

My home.component.ts look like this and I want to todasGuias() only make another request at a time.我的home.component.ts看起来像这样,我想todasGuias()一次只发出另一个请求。

    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:我的home.service.ts看起来像这样:

 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?有帮助吗?

You want to use the rxjs operator switchMap to achieve this:您想使用 rxjs 运算符switchMap来实现此目的:

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. range生成一个 Observable,每个数字从 1 到 TotalPages。 switchMap then maps each number to an Observable executing the http request. switchMap然后将每个数字映射到执行 http 请求的 Observable。 As switchMap only retains one subscription internally all the requests are made sequentially.由于switchMap在内部仅保留一个订阅,因此所有请求都是按顺序进行的。 If one request fails, the Observable will also fail.如果一个请求失败,Observable 也会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM