0

I can't show data in HTML from my API response because type of response is an Object and I couldn't convert to Array.

This is the response from API:

enter image description here

This is my service that works doing HTTP request to my API

 url: string = 'http://localhost:3000/aduanas/'
  constructor(public aduanas: AduanasService, private http: HttpClient) { }

 
  // getInfo(){
    
  //   console.log();
  // }

   getInfoAduanas():Observable<Aduanas>{
    return this.http.get<Aduanas>(`${this.url}${this.id.value}`)
  }
}

This is my interface:

export interface Aduanas {
    id:                 number;
    estado:             string;
    nombre:             string;
    telefono:           string;
    horario_sem:        string;
    horario_fin:        string;
    direccion:          string;
    tipo:               string;
    agentes:            string;
}

This is my component where I subscribe it

 customList:Aduanas;
  id = this.aduanas.markerId;
  constructor(private modalController: ModalController, public aduanas: AduanasService, public api: ApiService) { }

  ngOnInit() {

   
    this.api.getInfoAduanas().subscribe( data => {
      this.customList = data;

      console.log(this.customList);
    });
  }

I get this error:

enter image description here

And this is my HTML component:

enter image description here

Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
  • Does this answer your question? [How to iterate object keys using \*ngFor](https://stackoverflow.com/questions/41396435/how-to-iterate-object-keys-using-ngfor) – pascalpuetz Oct 24 '20 at 22:51
  • 2
    `ngFor` is used to iterate an array... If you just want to display the field `customList.nombre`, just remove the `*ngFor` prop and change `{{c.nombre}}` to `{{customList.nombre}}` (Additional null checks might be required). – EdgeNeko Oct 25 '20 at 04:54

2 Answers2

1

You are getting an Object from the API response and *ngFor is used to iterate over arrays to display values in the template. If you want to iterate over an object you should use Object.keys() method in the template.

HTML :-

<div class="text-align:right" *ngFor="let key of Object.keys(customList)">
  <h2 class="title1"> Key-> {{key}} and value is -> {{customList[key]}}</h2>
</div>

TS :-

  customList:Aduanas;
  id = this.aduanas.markerId;
  Object = Object;


  constructor(private modalController: ModalController, public 
  aduanas:AduanasService,public api: ApiService) { }
    
  ngOnInit() {
     this.api.getInfoAduanas().subscribe( data => {
         this.customList = data;
         console.log(this.customList);
      });
   }
Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
0

You can simply put on on middle brackets

 this.api.getInfoAduanas().subscribe( data => {
  this.customList = [data];

  console.log(this.customList);
});