Reputation: 25
I am using angular
Trying to call an api and retrieve data from it however it is throwing this error.
core.js:4352 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
my service looks like
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { User } from '../Models/user.model';
@Injectable({
providedIn: 'root'
})
export class DataService {
apiUrl = 'myurl is in here but i cannot show'
constructor(private _http: HttpClient) { }
getUsers(){
return this._http.get<User[]>(this.apiUrl);
}
}
user model looks like
export class User {
alertId: any;
itemId: string;
title: string;
description: string;
categoryId: any;
riskId: any;
sourceId: any;
startDate: any;
endDate: any;
link: string;
countryId: any;
countries: string;
keywordMatches: string;
keywordsMatched: 0;
createdDate: any;
createdBy: any;
isDeleted: true;
deletedDate: any;
deletedBy: any;
latitude: 0;
longitude: 0;
notes: string;
customerId: any;
formattedAddress: any;
firstname: any;
surname: any;
email: string;
phone: string;
smsEnabled: true;
customerName: string;
homeCountryId: any;
travellerTagId: 0;
}
This t.s component using it
import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/Models/user.model';
import { DataService } from 'src/app/Services/data.service';
@Component({
selector: 'app-side-nav-alerts',
templateUrl: './side-nav-alerts.component.html',
styleUrls: ['./side-nav-alerts.component.css']
})
export class SideNavAlertsComponent implements OnInit {
users$: User[];
constructor( private dataService : DataService) { }
ngOnInit(){
return this.dataService.getUsers()
.subscribe(data => this.users$ = data)
}
}
HTML
<div *ngFor = 'let user of users$' style="text-align: center;">
<h2>{{user.name}}</h2>
</div>
any ideas on how I could use this to loop over ? I essentially just wanna loop over it and display the info collected from the api I understand that maybe I need to convert this into another data type but I am unsure on how to do this.
Upvotes: 1
Views: 699
Reputation: 1743
You should try:
ngOnInit(){
this.users$ = this.dataService.getUsers()
}
instead of
ngOnInit(){
return this.dataService.getUsers()
.subscribe(data => this.users$ = data)
}
Since data is actual data and not a Subscription
resp. Observable
.
And btw there's no reason for your ngOnInit
to have a return statement.
Turn
users$: User[];
into
users$: Observable<User[]>;
Inside your html you need to use the async pipe like so:
*ngFor = 'let user of (users$ | async)' style="text-align: center;"
Upvotes: 2