简体   繁体   中英

Angular 4 Displaying Data From Rest API

I'm having problems displaying data from my local express.js REST API, which is structured like this:

 people: [{ surname: 'testsurname', name: 'testname', email: 
 'testmail@gmail.com', 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 (ie 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?

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

WORKING DEMO

You should do this to print your JSON structure " Array of object "

   <div *ngFor ="let person of _peopleArray">
      <div> {{person.name}} </div>
   </div>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM