1

I'm trying to access an API that returns a JSON with some data that I then need to present in my component html by using ngFor because it's an object. Inside the http.get function if I console.log the returned data, it appears fine. But when I try to present it in my view, it's not working.

Here is my component.ts:

import { HttpClient } from '@angular/common/http';

export class AnonimoComponent implements OnInit {
    public medicamentos: Object;

    private baseURL = 'http://website.com/api/medicamentos';

    constructor(private http: HttpClient) {  }

    ngOnInit() {
         this.getMedicamentos();
    }

    getMedicamentos(){
        interface MedicamentoResponse {
            id: number;
            Name: string;
            Preco: number;
        }

        this.http.get<MedicamentoResponse>(this.baseURL).subscribe((data) => {
             this.medicamentos = data;
             console.log("First:\n" + this.medicamentos);
        });
    }
}

Here is my html:

<ul>
    <li *ngFor="let med of medicamentos$ | async">
        {{med}}
    </li>
</ul>

However, it's not presenting anything. Any ideas?

Adam Silva
  • 1,013
  • 18
  • 48

3 Answers3

1

Change

*ngFor="let med of medicamentos$ | async"

to

*ngFor="let med of medicamentos"
  • You can't use async because medicamentos is not an Observable, you assigned the result directly in the subscribe in your component's code
  • Casing and variable name are critical, you can't add a character like $ at the end of the variable name in the template and have it still work.

Finally you should validate that what is being assigned to medicamentos is actually an array, verify the response in your browser's debugger.

Igor
  • 60,821
  • 10
  • 100
  • 175
1

If you use the |async pipe, you can't use .subscribe().

It should be

getMedicamentos(){
    this.medicamentos = this.http.get<MedicamentoResponse>(this.baseURL);
}

If you use

 this.medicamentos = data;

then you don't need |async

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • What I'm getting from the api is: `id:4,name:"Amoxapina",preco:12`, and now the console is giving this error: `Cannot find a differ supporting object '[object Object]' of type 'Amoxapina'. NgFor only supports binding to Iterables such as Arrays.` – Adam Silva Dec 08 '17 at 18:58
  • 1
    Sounds like you're looking for https://stackoverflow.com/questions/41396435/how-to-iterate-object-object-using-ngfor-in-angular-2/41396558#41396558 – Günter Zöchbauer Dec 08 '17 at 18:59
0

*ngFor is not work with JSON..

You have to Convert it to Array.

Try This

this.medicamentos = data.json();
Darshit Hedpara
  • 660
  • 6
  • 17