Reputation: 340
I'm having problems displaying data from my local express.js REST API, which is structured like this:
people: [{ surname: 'testsurname', name: 'testname', email:
'[email protected]', status: 1, activity: 'Office' }
I have a people service where I get the data, it looks like this:
export interface People {
surname: String;
name: String;
email: String;
status: Boolean;
activity: String;
}
@Injectable()
export class PeopleService {
private _peopleURL = "http://localhost:8080/api/people";
constructor(private http: HttpClient) {
console.log('init PS')
}
getPeople(): Observable<People[]> {
return this.http
.get(this._peopleURL)
.map((response: Response) => {
return <People[]>response.json();
})
}
}
This is my PeopleComponent.ts code
export class PeopleComponent implements OnInit {
_peopleArray: People[];
constructor(private ps: PeopleService)
{ }
getPeople(): void {
this.ps.getPeople()
.subscribe(
resultArray => this._peopleArray = resultArray,
error => console.log("Error :: " + error)
)
}
ngOnInit(): void {
this.getPeople();
}
Now I'm trying to display the data (i.e. the name) in my 'People' component.html like so:
<div> {{people.name}} </div>
When I start my app I get an error saying
'TypeError: Cannot read property 'name' of undefined at Object.eval [as updateRenderer]
Can anyone explain to me what I missed and what I need to be doing in order to display the data?
Upvotes: 0
Views: 142
Reputation: 28642
You response is json array
.try following code snippet.
<div *ngFor ="let p of people">
<div> {{p.name}} </div>
</div>
Update
Change your service method as shown below.The default value that returns new HttpClient is Object. It automatically calls response.json()
internally.
getPeople(): Observable<People[]> {
return this.http
.get<People[]>(this._peopleURL);
}
Check out following working demo
Upvotes: 1
Reputation: 59
You should do this to print your JSON structure "Array of object"
<div *ngFor ="let person of _peopleArray">
<div> {{person.name}} </div>
</div>
Upvotes: 0
Reputation: 10127
You don't even have "people" field in your component, you're setting it to "_peopleArray".
But even if you change it to
<div> {{_peopleArray.name}} </div>
it still won't work since _peopleArray is, well, an array.
You can iterate over array objects with *ngFor or access only first or nth element of the array like so
<div> {{_peopleArray[0].name}} </div>
Upvotes: 0