Home > Enterprise >  Angular: get request
Angular: get request

Time:05-09

i have an issue with displaying data in console. I am trying to retrieve log data in the console but i am getting null without knowing what the problem is. This is my code:

Service.ts

 getItemById(id:number): Observable<any> {
    return this.http.get<any>(`${this.API}/${id}`).pipe(catchError(this.handleError
    ));
  }

  private handleError(httpErrorResponse:HttpErrorResponse){
    if(httpErrorResponse.error instanceof ErrorEvent){
      console.error(httpErrorResponse.error.message)
    }
    return of(null)
  }

Component.ts

showItem(id: any) {

   
    this.ItemService.getItemById(id).subscribe((data: any) => {
      console.log(data)

      this.log = data;
      
    })
  }

html button

        <td><button  (click)="showItem(log.id)">{{buttonName}}</button></td>

when i click the button the response is giving 200 in the network section enter image description here

but the console is returning a null, it does not return the payload. enter image description here

Any solutions ?

CodePudding user response:

Since you have an error, try first with a simpler solution:

Service.ts

getItemById(id:number): Observable<any> {
   return this.http.get(`${this.API}/${id}`);
}

Component.ts

showItem(id: any) {
   
   this.ItemService.getItemById(id)
   .subscribe(
      (data: any) => {
         console.log(data);
         //this.log = data;      
    });

}

After this, see if your API works (if it gets data).

Once you check this,

  1. If it doesn't return anything, your solution was right, and the problem is in the back.

  2. If it is returning data, there was a problem. Then, in order to find out what is going on, you can try to left this simplified version and try the error directly in the subscription, with catchError or simply managing the "path" of error (something like this:)

this.ItemService.getItemById(id)
   .subscribe(
      (data: any) => {
         console.log(data);
         //this.log = data;      
      },
      err => {console.log(err);} // You'll get the whole object, 
                                 // If you get [object object] you shoud use the specifics fields, something like console.log(err.error.message) or something like that... (look them up on the internet)
    );

CodePudding user response:

I just figured out that i had to add the responseType to the url in the service.ts. This link was useful : Angular HttpClient "Http failure during parsing"

  • Related