JSON data is not displaying on html

I worked in 2 other ionic4 projects and this error never happened to me.

I’m trying to get a category details by id, so I copied a code from another project that works properly, but when I tried to display the category’s name it says
“Uncaught (in promise): TypeError: Cannot read property ‘name’ of undefined
TypeError: Cannot read property ‘name’ of undefined”

My service :

fetchCategory(id: any): Observable<Category> {
      return this.http.get<Category>(`${this.base_url+"category/"}${id}`);

My category page:

 getSubCategoryDetail(id:number) {
    return this.repVertAPI.fetchCategory(id).subscribe(
     data => {
        this.category = (JSON.stringify(data)) ;
      } )

my html :

  <ion-card  *ngIf="category">
        <ion-card-subtitle>Image ici</ion-card-subtitle>


I’m getting this json in my console :


I’m stuck here …

Your data is in an array, so you need to take the element u want out of it

This.category[0] has the element with data u want to use to show the element

It did not work, I already did that but got an error

displays “d” no way that I can display that JSON properly ?

well, It worked when I did an ngFor to the whole object, so I will post the code maybe it could help someone in the future .

ngOnInit() {

    let id = this.route.snapshot.paramMap.get('id');

    this.repVertAPI.fetchCategory(id).subscribe(data =>{

      // console.log('detalles: ',result);

      this.category =data;



the HTML :

<ion-card *ngIf="category" >



      <ion-card-subtitle *ngFor="let item of category;"  style="color: black;">{{item.name}}</ion-card-subtitle>


Imho, solving in the template with ngFor only makes sense if you in the future expect more entries in this.category which would also ideally require you to rename that name to this.categories.

If that is not expected, then your data provider (where you get the data) should not use [ ] in returning the value. Makes mostly little sense to specify a single object as an array.

If that is not an option for you then I think you should not use ngFor and type this.category=data[0] so you at least get the first object in the array. If you want to be safe, you can test data.length>0 so you don’t get undefined. On the other hand, you already test undefined with your ngIf

Either way, avoid trying to solve API data issues in the template. It gives lots of extra work on your end.

Key to understanding this bug is having understood the data type of the returning value as per original post. Will be good for future to look at that sharply. Mistake I still make once in a while - but with less despair now I know.

ps. did u see you are not closing the ion-card-header?

1 Like

Yep I fixed that, my bad

1 Like

I’ll go farther than @Tommertom here and flat-out declare the backend broken. By definition, ids are unique. A request for anything that specifies an id cannot return more than one entity.