Showing JSON data as a list in Angular 7

I'm encountering a problem trying to display JSON data in a list format. It seems like something is missing because the data isn't showing up. Below is the code I've been using:

Service:

 getData() {
    this.http.post('http://localhost/api/Acc/GetData', "").subscribe(res => {
    return res;
   });
 }

Component:

  constructor(private api: ApiService) {
     var data = api.getData();   
  }

Template:

<mat-list>
<mat-list-item *ngFor="let item of data">
<h4 matLine> {{item.Field1}} </h4>
</mat-list-item>
</mat-list>

Upon inspection, I can identify some areas that may be causing issues:

  1. I am uncertain if getData is correctly returning the data.

  2. I am unsure if the constructor is effectively storing the data. I have tried alternative methods but none seem to work.

Answer №1

Learn how to retrieve a list of objects from a server in Angular's Tour of Heroes tutorial in section 6, titled HTTP - Get Heroes with HTTPClient:

/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
}

For more information and guidance on importing necessary modules for this task, refer to the rest of the tutorial at https://angular.io/tutorial.

Answer №2

Ensure that your getData() method returns an Observable to handle asynchronous data fetching.

Within your component, subscribe to the Observable and display the received data accordingly.

@Component({
  selector: 'app-some-data',
  templateUrl: './some-data.component.html',
  styleUrls: ['./some-data.component.css']
})
export class SomeDataComponent implements OnInit {
  data: any[];

  constructor(private api: ApiService) { }

  ngOnInit() {
    this.api.getData().subscribe(data => this.data = data);
  }
}
<div>
  <div *ngFor="let item of data">{{item | json}}</div>
</div>
@Injectable({
  providedIn: 'root',
})
export class ApiService {

  // constructor, etc.

  getData(): Observable<any[]> {
    return this.http.post<any[]>('http://localhost/api/Acc/GetData', "");
  }
}

You can also use the async pipe in the HTML template to subscribe to the observable.

@Component({
  selector: 'app-some-data',
  templateUrl: './some-data.component.html',
  styleUrls: ['./some-data.component.css']
})
export class SomeDataComponent implements OnInit {
  data: Observable<any[]>;

  constructor(private api: ApiService) { }

  ngOnInit() {
    this.data = this.api.getData();
  }
}
<div *ngIf="(data | async) as items">
  <div *ngFor="let item of items">{{item | json}}</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

Encountering a bug in Angular 11 while fetching data from the backend to display on the screen - facing an issue with trying to access property 'values' of an undefined variable

I am currently working on retrieving data from the backend/api and attempting to display it using *ngFor. However, I am encountering the following errors: Cannot read property 'values' of undefined Below are the components, service codes, and ...

What is the process for embedding images in Angular that are stored in a directory other than assets?

I am working on an Angular Application with a particular structure outlined below: Structure Within the structure, there is a directory labeled backend (highlighted in yellow) containing other directories. An example of a valid path within this structure ...

How can I store various data types in a single array in TypeScript?

I have a scenario I need help with. Let's say we have two interfaces, Cats and Dogs. How can I create an array that can store both Cats and Dogs? interface Cats { name: string; age: number; } interface Dog { owner: string; } const cat1: Cat ...

Is it possible to update the Backend IP address after setting up the Angular Frontend and hosting it with nginx?

Our project involves utilizing an Intel NUC with Ubuntu 18.04 for a WebInterface. The backend is up and running on the device, connecting to the frontend through a WebSocket. The front end is powered by Angular and hosted using nginx. However, we've e ...

Exploring ag-Grid: Best Practices for Unit Testing ICellRendererAngularComp Components

I have developed a custom control that utilizes ICellRendererAngularComp from ag-grid with a series of actions and incorporated it into my main ag-grid component. However, I am unsure about how to write tests for this custom control in order to mock the pa ...

What causes the node_modules folder to become corrupted when publishing an AspNetCore2 project with Visual Studio?

During the development of my AspNetCore project using Kendo, Angular5, and AspNet Mvc, everything was running smoothly. However, when trying to publish the project, I encountered a strange issue where it breaks. https://i.sstatic.net/2xQ1Q.png I then cam ...

Steps to prevent uib-timepicker from automatically adjusting time based on the Browser Timezone

Currently in my database, timestamps are stored in UTC format. On the frontend, I am implementing uib-timepicker for time editing and updating purposes. However, I do not want uib-timepicker to automatically convert the time from the server's timezone ...

Facebook sharing woes: Angular app's OG meta tags fail to work properly

Trying to figure out how to properly use og tags for the first time. I'm working on an Angular application and need to share my app link on Facebook with all the necessary tag information included. In my index.html file, I've inserted the follow ...

Securing your Angular 5 source code

We are in the process of developing a cutting-edge product using Angular 5 and Node.js. This new product will be implemented directly at the customer's local environment. However, one major concern we have is how to safeguard our code from potential ...

Several asynchronous calls are made, each returning a boolean value without waiting for them to

One challenge I am encountering is that the searchbar displays "No results found" before showing actual results. This issue is not related to the frontend; rather, it occurs due to the asynchronous nature of the calls. Calls without results complete faster ...

Calculating numbers with Math.ceil will result in an increase of 1

After using Math.ceil, one value was rounded up to 50 and the other to 80. However, when I added these two values together, the result unexpectedly turned out to be 131. console.log(Math.ceil(e.currentTarget.clientHeight) // 50 console.log(Math.ceil(e.cu ...

Data not being retrieved by HTTP GET request

I encountered an issue with my API where I made three Get requests using the same function but different URLs to differentiate between them. However, even though the provider returns the data in steps, the page response function does not receive it and sho ...

Assign the chosen option in the Angular 2 dropdown menu to a specific value

Currently, I am utilizing FormBuilder in order to input values into a database. this.formUser = this._form.group({ "firstName": new FormControl('', [Validators.required]), "lastName": new FormControl('', [Validators.required]), ...

Guide on executing get, modify, append, and erase tasks on a multi-parameter JSON array akin to an API within Angular

I have a JSON array called courseList with multiple parameters: public courseList:any=[ { id:1, cName: "Angular", bDesc: "This is the basic course for Angular.", amt: "$50", dur: & ...

Redeclaring block-scoped variable 'reducer' is not allowed in TypeScript

I encountered an error message Cannot redeclare block-scoped variable 'reducer' when running sample code from a book using tsc. I'm unsure of the reason behind this issue. tsc -v // Version 2.1.0-dev.20160726 Next, I executed ts-node in t ...

I'm encountering a Typescript error where I'm unable to assign a function to RefObject.current and it's indicating that the function is not callable

Does anyone know why assigning a function type to a ref.current type is causing me issues? useEffect(() => { savedHandler.current = handler; // ERROR HERE: }, [handler]); TS2741: Property 'current' is missing in type '(e: Chang ...

The values obtained from an HTTP GET request can vary between using Curl and Ionic2/Angular2

When I make a GET request using curl in the following manner: curl https://api.backand.com:443/1/objects/todos?AnonymousToken=my-token I receive the correct data as shown below: {"totalRows":2,"data":[{"__metadata":{"id& ...

Material 2's portal host fails to display the specified template portal

Check out the Demo Plunker here: https://plnkr.co/edit/Ye8MAUmrMEQKnPt93TjT?p=preview I'm following the guidance from Material 2 documentation in order to establish a template portal that will be displayed within a nearby host (although my ultimate g ...

how can I update a class of an element when the input box is disabled in angular?

Is there a way in Angular to change the class of a separate element (calendar icon button) when it detects that an input textbox is disabled? I have a disabled input type textbox and I want the class of the calendar icon button to be changed based on its d ...

Problem with overlapping numbers in the Vis network

I am currently working on a project using Angular 8 and Visnetwork. Everything is going well, but I am facing an issue with overlapping numbers on lines. Is there a way to adjust the position of the numbers on one line without separating the lines? Can s ...