Rendering Information in Angular 4 Through Rest API

Encountering issues displaying data from my local express.js REST API, organized as follows:

 people: [{ surname: 'testsurname', name: 'testname', email: 
 '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681c0d1b1c05090104280f05090104460b07">[email protected]</a>', status: 1, activity: 'Office' }

An excerpt from my people service where data retrieval is defined:

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 section showcases the code in my PeopleComponent.ts file:

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();
  }

The next step aims to display the data (specifically the name) in the 'People' component HTML page using:

<div> {{people.name}} </div>

Nevertheless, upon starting the application, an error occurs stating

'TypeError: Cannot read property 'name' of undefined at Object.eval [as updateRenderer] 

Could someone shed light on what I may have overlooked and provide guidance on showcasing the data properly?

Answer №1

Your response is in JSON format, try using the code snippet below.

<div *ngFor ="let p of people">
      <div> {{p.name}} </div>
   </div>

Update:

To update your service method, use the code provided below. The default value that new HttpClient returns is an Object, which automatically calls response.json() internally.

getPeople(): Observable<People[]> {
    return this.http
      .get<People[]>(this._peopleURL);

  }

Take a look at the following working demo:

WORKING DEMO

Answer №2

In the component, there is no "people" field present as you are assigning it to "_peopleArray".

Even if you modify it to

<div> {{_peopleArray.name}} </div>

it will not function correctly because _peopleArray is an array.

To properly access array objects, you can use *ngFor for iteration or retrieve specific elements from the array like this

<div> {{_peopleArray[0].name}} </div>

Answer №3

If you want to display your JSON structure as an "Array of object", follow these steps:

<div *ngFor ="let individual of _individualsList">
      <div> {{individual.name}} </div>
   </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A convenient utility for generating React components with pre-populated Tailwind CSS classes

When it comes to extracting local Tailwind-styled components, I tend to do it like this: const Container: React.FC = ({ children }) => ( <div className="bg-white px-5 py-5"> {children} </div> ); To simplify this process, I ...

Angular 2 failing to recognize service variable changes initiated from component

Hello there, I'm currently facing a challenge with updating my component to reflect the correct value of a service variable whenever it changes. Here's what I have so far: Snippet from Component1 HTML {{icons | json}} Component1 Code icons: ...

What is the process for generating a file in Node and Express on my server and subsequently transmitting it to my client for download? My technology stack includes NextJS for both frontend and backend operations

How can I generate a file using Express and Node on my server, and then successfully download it to the client? My tech stack includes NextJS for both frontend and backend, and with React as the frontend framework. I'm facing difficulty figuring out h ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

"Despite not preferring to use the CORS wildcard, I am encountering a CORS wildcard error

I'm currently in the process of developing a web application using node, express, and Vue3 My goal is to submit a form to an endpoint located on my router at '/match/matchpost'. I have previously tested this endpoint successfully. However, ...

Angular - Utilizing nested arrays for efficient file uploading

I am currently working on building a file uploader using Angular. My goal is to be able to upload different types of files, with each button capable of uploading multiple files at once. However, I am running into an issue where the uploaded files are not b ...

A guide on utilizing React hooks to randomly divide a group into two teams

Is there a way to randomly divide players from an array into two teams, ensuring that each team has an equal number of players if the total is even. If it's an odd number, having one extra player in either team is acceptable. I have written a JavaScr ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

Shifting successive elements in an array alternates

I have been working on a pick list component and have come up with the following layout https://i.stack.imgur.com/TnHAp.gif Whenever I try to move consecutive items, it keeps toggling between those two Here's a snippet of my code: moveDown(){ ...

What is preventing me from including an additional parameter in a function in TypeScript?

I am currently developing a task management application. I am facing an issue while attempting to incorporate the event and items.id into a button function for actions like delete, edit, or mark as completed. While this functionality works smoothly in pla ...

Best practices for incorporating CSS and JS files into an Angular deployment

I am currently in the process of integrating an Admin Template that I previously used in a traditional PHP application into a new Angular project. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel= ...

How to Delete an Element from a JSON Array in Scala

I received a JSON response that looks like this: [ { "id": 2202, "name": "name one", "phone": "+62888888", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98fbedebecf7f5fdead8fff5f9 ...

Aggregate the data chunks in the antd table into groups

I've been struggling to find a solution for this specific issue. My goal is to group the data in my table based on a particular field, but I need it to be styled as depicted in the image linked below. https://i.stack.imgur.com/OsR7J.png After looking ...

Activate the event when the radio button is changed

Is there a way to change the selected radio button in a radio group that is generated using a for loop? I am attempting to utilize the changeRadio function to select and trigger the change of the radio button based on a specific value. <mat-radio-group ...

Is it possible to implement a redirect in Angular's Resolve Navigation Guard when an error is encountered from a resolved promise?

I have integrated Angularfire into my Angular project and am utilizing the authentication feature. Everything is functioning properly, however, my Resolve Navigation Guard is preventing the activation of the component in case of an error during the resolve ...

Sorting an array of objects in Typescript using a dynamic property name for generics

My goal is to develop a versatile, typed function that can arrange an array of objects by a numerical value housed under a dynamically named property within each object. Here is my current progress: export const sortByNumber = <T, K extends keyof T> ...

Leveraging ES Module packages in Azure TypeScript Function Development

I'm encountering an issue while trying to utilize the p-map package in my Azure Function. The error message that I'm getting is as follows: A Worker failed to load function: 'serverless' with function id: '<id>'. Result: ...

The invocation of res.json() results in the generation of CastError

An issue occurs with CastError when using res.json() with an argument: CastError: Failed to cast value "undefined" to ObjectId for the "_id" field in the "Post" model Interestingly, using just res.status(), res.sendStatus(), or res.json() without argument ...

Express router takes on a distinct path when including a parameter

I currently have two different routes set up. When attempting to access the /name route and pass a name param, it successfully reaches the /name endpoint without any parameters. However, as soon as I modify it to '/name/:name' in order to retrie ...