Issue with displaying data in HTML even though it appears in the console log in Angular framework

I am able to retrieve JSON data from my server-side and view it on the console log, but I am encountering difficulties rendering it on the HTML page. Could this be due to incorrect syntax?

I am attempting to access data from my MongoDB and display it using Angular. I have tried incorporating various suggestions found online to present the data in a table with filtering, sorting, etc. It seems like there might be an issue with my *ngFor directive. I have experimented with ' let ticket of tickets.obj' among others, but no success.

This is my TypeScript file:

this.http.post(environment.apiBaseUrl + '/filter', JSON.stringify(filterOptions), httpOptions)

.subscribe( res => {
  this.tickets = res;
  this.tickets = Array.of(this.tickets);
  this.totalPages = Math.ceil(this.totalRowCount / this.rowCount);
  console.log('Fetched Tickets');
  console.log(this.tickets);
},
  err => {
    console.log('Error fetching tickets');
  }
);

HTML

      <tbody>
        <tr *ngIf="tickets.length == 0">
          <td colspan="4" align="center" valign="middle">
            No Records Found.
          </td>
        </tr>
        <tr *ngFor="let ticket of tickets; let i = index;">
          <td>{{i+1+offset}}</td>
          <td>{{ticket.resolution}}</td>
          <td>{{ticket.ticketId}}</td>
          <td>{{ticket.status}}</td>
        </tr>
      </tbody>

The table remains empty despite the fact that data appears on the console log.

https://i.sstatic.net/oNDzc.jpg

Answer №1

You can specify the array to bind as the obj property inside an element of the result array.

This example shows how it can be done:

...
  subscribe( response => {
  this.tickets = response[0].obj;
...

Answer №2

There seems to be an issue in the following area: - The response is in array format, with the first element being the necessary information. You can assign this.tickets = res[0].obj to get the desired result. I hope this solution proves helpful to you :)

Answer №3

If you're working with a JSON response array stored in the obj variable, try replacing the code below to make it function properly:

this.http.post(environment.apiBaseUrl + '/filter', JSON.stringify(filterOptions), httpOptions)
.subscribe( res => {
  this.tickets = res.obj; //obj is an array of elements
   this.tickets = Array.of(this.tickets);
  this.totalPages = Math.ceil(this.totalRowCount / this.rowCount);
  console.log('Fetched Tickets');
  console.log(this.tickets);
},
err => {
    console.log('Error fetching tickets');
  }
);

I hope this solution works for you!

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

Tips for correctly implementing an authorize function in TypeScript with NextAuth.js

Trying to implement the Credentials Provider in NextJs ("next": "^12.0.7") and NextAuth ("next-auth": "^4.1.2") using TypeScript has been a challenge. I am encountering difficulties in getting the function to work co ...

Angular tutorial: Accessing individual HTML elements within the *ngFor loop

I am facing an issue trying to access the "box-message" class using "document.querySelectorAll('.box-message')" within a tree structure where the "*ngFor" directive is utilized. After making an "http rest" request, the *ngFor directive finishes ...

Tips for adding type definitions to an ObjectConstructor in your Typescript code within .tsx files

When I use my custom object constructor for object.keys and .values in .ts files, everything works fine. However, when I try to use them in .tsx files, the compiler interprets it as JSX and I get an error. const myObject = (<TypedObject>Object).keys( ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...

How to dynamically track changes in Angular2 form fields: Using the formbuilder to

Currently, I'm working with ionic2 and angular2. I have a form constructed using formbuilder but I am looking to monitor any new changes made to a specific input. ionViewDidLoad() { this.purchaseDataForm = this.formBuilder.group({ kms: ['& ...

Whenever I attempt to make changes to the React state, it always ends up getting reset

Currently, I am attempting to utilize Listbox provided by Headless UI in order to create a select dropdown menu for filtering purposes within my application. However, the issue I have encountered is that whenever I update my "selectedMake" state, it revert ...

When passing parameters through a URL in TypeScript, the display shows up as "[object object]" rather than as a string

Hey there! I'm trying to pass some string parameters to my URL to fetch information from an API. Everything seems fine, and when displayed in an alert, the URL looks exactly as it should (no [object, object] issue). var startDate = "2020-09-20"; var ...

Efficiently load Angular modules only when needed on different routes

My Angular project utilizes lazy loading for modules and below are the defined routes: { pathMatch: 'full', path: '', loadChildren: () => import('./pages/landing/home-page/home-page.module').then(m => m.Hom ...

Troubleshooting: Issue with Button Layout in Ionic's ItemSliding Component

How can I create a list item that allows swiping to reveal an archive button? The requirement is for the icon to appear to the left of the text. I'm referring to the documentation on Button Layout: https://ionicframework.com/docs/api/components/item ...

What is the best way to filter specific data types when using ngFor in Angular?

As I loop through the array named "fruits," which contains objects of type "FruitService" that I created, I want to display each element. However, when I delete them (I know it's strange, no database involved), they turn into type "undefined" and star ...

View the material expansion panel by scrolling without turning off the animation

Whenever a MaterialExpansionPanel opens, I use the scrollIntoView method. opened(i) { setTimeout(() => this.panels.toArray()[i].nativeElement.scrollIntoView({ behavior: 'smooth' } )); } Although it works, if the animation ([@. ...

Differences between Angular TS Lint onInit and ngOnInit

My TS Lint issue warned me to implement the OnInit interface and included a link to this page: https://angular.io/docs/ts/latest/guide/style-guide.html#!#09-01 I'm curious, what sets apart `onInit` from `ngOnInit`? Both seem to work just fine for me. ...

Is it possible for the binding model of Mat-Checkbox to be optional or null?

Greetings everyone! I am a newcomer to the world of Angular, where I have successfully created a dynamic list of checkboxes. However, I have encountered a challenge when trying to bind selected values from an API to these checkboxes. <div *ngFor="let b ...

Having trouble retrieving information from a JSON object? Unable to retrieve property 'company_about' of an undefined object?

Here is the JSON data I have: [ { "id": 1, "job_id": 1, "company_profile": "Sales and Marketing", "company_about": "Established in 1992 , it is a renouned marketing company", "company_product": "Ford,Mustang,Beetle", "key_skills": ...

Unable to retrieve data from response using promise in Angular 2?

I am struggling to extract the desired data from the response. Despite trying various methods, I can't seem to achieve the expected outcome. facebookLogin(): void { this.fb.login() .then((res: LoginResponse) => { this.acce ...

Downloading a PDF in a Next.js application

How can I add a button or link that will instantly download my PDF portfolio when clicked? I am currently working on my resume section and would like to provide users with the option to easily download my CV. Is there a way to do this, and if so, how can ...

Create Office Script calculations with quotations included

I am currently attempting to create an Excel office script formula for a cell. Are there any tips on how to insert a formula with quotes into a cell? For example, the following works fine: wsWa.getCell(WaRangeRowCount, 9).setFormula("= 1 + 1"); ...

Typescript libraries built specifically for unique custom classes

I am currently exploring the most effective method for creating a class library in Typescript and deploying it to NPM along with a definitions file. The classes within the library serve as models that are utilized by multiple RESTful services. Some of the ...

The chosen sidebar item fails to show the respective component

Is there a way to show a component when the user clicks on the sideNav? Currently, I have managed to display the SideBarNavigation using ng-simple-sidebar. However, when I click on a sidebar item, the component opens as a new page instead of being display ...

The Spring Boot REST application is unexpectedly returning HTML instead of JSON, causing confusion for the Angular application which is unable to recognize the

I am struggling with my Spring Boot application that was generated using . I am having difficulty getting it to return JSON instead of HTML. Here is a snippet of the code: [@CrossOrigin(origins="http://localhost:4200",maxAge=3600) @RestController @Request ...