Request entering infinite loop with Httpclient

Asked

Viewed 29 times

1

I’m getting a get for my local API but the service method seems to loop running countless requests to the server

I have the app.component.html and inside I have the following code


<div *ngIf="checkProfile()">
  <!-- <navbar *ngIf="false"></navbar> -->
</div>

<router-outlet *ngIf="!userSignedIn()"></router-outlet>

the method checkProfile() should return a Boolean to enter or not div.

Aki is the method in app.component.ts:


  public checkProfile() {

    if (this.userSignedIn()) {
      this.profileService.getById(1)
        .subscribe(
          res => {
            console.log(res)
            return true;
          },
          err => {
            console.log(err)
            return true; 
          }
        )
    }

  }


  //retorna um boolean
  public userSignedIn(){
    return this.authService.userSignedIn();
  }

the service being called and profile.service.ts:


  public getById(id: number): Observable<Profile> {
    let url = `${this.profileUrl}/${id}`;
    
    return this.http.get<Profile>(url)
      .pipe(
        catchError(this.handleErrors),
        map(response => this.responseToProfile(response))
      )
  }

  private responseToProfile(response: any): Profile {
    return new Profile(
      response.data.attributes['user-id'],
      response.data.attributes.name,
      response.data.attributes.surname,
      response.data.attributes.birth,
      response.data.attributes.cpf,
      response.data.attributes.phone,
      response.data.id
    )
  }

  private handleErrors(error: HttpErrorResponse) {
    console.log("SALVANDO O ERRO EM UM ARQUIVO DE LOG - DETALHES DO ERRO => ", error);
    return throwError(error);
  }

and Aki is the API console showing the countless identical requests:

Console-1

Console-2

  • 1

    It is not good to use functions like this in the template. Try calling your endpoint first and setting a variable in your component

  • I injected Oninit, implemented in the class and created the ngOnInit method, tbm created the variable in public profileExist: boolean = null; and called in the template. Within onInit a request has not made endless requests, however and I have done so using a statical Id value Id: '1', within onInit my Currentuserdata.id generated by the post page refresh authentication class nn arrives, in the life cycle it is generated dpois, tried to use ngAfterContentChecked but Aki within the infinite requirements tbm occur

No answers

Browser other questions tagged

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