Consume REST IONIC3

0

Hello, I am new to the web and Ionic3 and I have a problem, I followed a tutorial to consume a rest API, I was able to bring the list with the users, however I am trying to bring a specific user and show it on screen if I I change the URL to the user it shows me this error

TabCepPage.html:10 ERROR Error: Cannot find a differ supporting object
'[object Object]' of type 'Leanne Graham'. NgFor only supports binding 
to  Iterables such as Arrays.

My app is like this:

provider: rest.ts

apiUrl = 'https://jsonplaceholder.typicode.com';

constructor(public http: HttpClient) {
  console.log('Hello RestServiceProvider Provider');
}

getUsers() {
  return new Promise(resolve => {
    this.http.get(this.apiUrl+'/users/1').subscribe(data => {
      resolve(data);
    }, err => {
      console.log(err);
    });
  });
}

ts of the page:

users: any;

constructor(public navCtrl: NavController, public restProvider: RestProvider) {
  this.getUsers();
}

getUsers() {
  this.restProvider.getUsers()
  .then(data => {
    this.users = data;
    console.log(this.users);
  });
}

and in HTML it looks like this:

<ion-item *ngFor="let user of users">
  <h2>{{user.name}}</h2>
  <p>{{user.email}}</p>
</ion-item>

Can anyone help me?

    
asked by anonymous 14.09.2017 / 21:54

1 answer

1

If you look at the error, you'll see that Ngfor is trying to iterate over a 'Leanne Graham' object which is not supported and is the name attribute returned by the API. Since you are returning only one object, your html will look like this:

HTML

<ion-item>
  <h2>{{user?.name}}</h2>
  <p>{{user?.email}}</p>
</ion-item>

Obs : If you use Ctrl + Shift + J, you will open the browser console (Chrome), and you can see how the object is being returned, / p>     

15.09.2017 / 13:19