0

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 class="btn btn-block btn-primary" (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 ?

Bash
  • 101
  • 11
  • 1
    So are you sure your api returns something? Doesn’t look like it does? What does it show when you simply open the api url in a browser tab? – MikeOne May 08 '22 at 16:14
  • The Api url is opening returning the payload in the browser, but not in the application itself – Bash May 09 '22 at 08:53

2 Answers2

1

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)
    );
0

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"

Bash
  • 101
  • 11