The mat table is not displaying the values from the API despite receiving the correct array

I recently made the decision to dive into learning Angular, but I've encountered some difficulties. Specifically, I'm struggling to populate a table with values retrieved from an API using MatTable. Despite receiving the correct values from the API, they just won't show up in the table without any error messages during compilation. I've attempted various solutions to tackle this issue, but none of them seem to work. Any assistance would be greatly appreciated.

HTML:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <ng-container matColumnDef="ID">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let element"> {{element.ID}} </td>
  </ng-container>
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>
  <ng-container matColumnDef="animaltype">
    <th mat-header-cell *matHeaderCellDef> AnimalType </th>
    <td mat-cell *matCellDef="let element"> {{element.animaltype}} </td>
  </ng-container>
  <ng-container matColumnDef="race">
    <th mat-header-cell *matHeaderCellDef> Race </th>
    <td mat-cell *matCellDef="let element"> {{element.race}} </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Typescript:

    import { AfterViewInit, Component, ViewChild, OnInit } from '@angular/core';
    import { MatTableDataSource } from '@angular/material/table';
    import { User } from 'src/app/models/user.model';
    import { Adoption } from 'src/app/models/adoption.model';
    import { AccountService } from '../services/account.service';

    @Component({
    selector: 'app-myadoptions',
    templateUrl: './myadoptions.component.html',
    styleUrls: ['./myadoptions.component.css']
    })

     export class MyadoptionsComponent implements OnInit {
      allAdoption: Adoption[];
      dataSource: MatTableDataSource<Adoption>;
      displayedColumns: string[] = ['ID', 'name', 'animaltype', 'race'];
      user: User;
      string: string;
      payload;

      constructor(private accountService: AccountService) {
      }

      ngOnInit() {
        this.adoptions();
      }

      public adoptions() {
      let resp = this.accountService.getAdoptions(this.getUserId());
      resp.subscribe(data => {
        this.dataSource = new MatTableDataSource(data);
        console.log(this.dataSource.data);
      });
      }

      getUserId() {
        this.string = localStorage.getItem('user');
        this.user = (JSON.parse(this.string));
           if (this.user.token) {
            this.payload = this.user.token.split(".")[1];
            this.payload = window.atob(this.payload);
            const userString = JSON.parse(this.payload);
            return parseInt(userString.UserID);
      }
     }

     }

Model:

    export class Adoption {
    id: number;
    name: string;
    animaltype: string;
    race: string;
    UserID: number; 
    text: string;
    adopted: boolean; 
     }

Console log: Console.log

Table: table

Answer №1

It seems like the data you need is nested under a property named data in the response from the getAdoptions method. However, you are currently loading the entire outer response object into the MatTable.

For example, your current code looks like this:

let resp = this.accountService.getAdoptions(this.getUserId());
      resp.subscribe(data => {
        this.dataSource = new MatTableDataSource(data);

But based on the console output of this.dataSource.data, it appears that the Adoption records are actually stored in a property named data within the response:

getAdoptionsResponse: {
  data: Adoption[];
}

If this is the case, you should update your code to:

let resp = this.accountService.getAdoptions(this.getUserId());
      resp.subscribe(response => {
        this.dataSource = new MatTableDataSource(response.data);

This will ensure that the data is loaded correctly into the MatTable.

To confirm or refute this, you can print out the value you receive from the getAdoptions subscription.

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

How can I detect the shift key press when an array key is pressed in Angular 2?

I have a collection of items that I want to implement file traversal behavior for, similar to a file explorer. This means that after selecting an item, if you hold down the shift key and press the down arrow, those items should also be selected. Below is ...

Differentiate input elements with custom styling

I'm experiencing an issue while trying to style a specific form field in Angular 7. The style doesn't seem to be applying properly. Below is my form structure: <ul> <li> <mat-form-field *ngIf="number"> <input ma ...

Having trouble converting an array of strings into a JSON ARRAY column in Snowflake

I am encountering an issue with an SQL column in my Snowflake table that is declared as the ARRAY data type. Specifically, when I attempted to perform a COPY INTO from a CSV file where one row contained a value for this column of ["A","B"], it resulted in ...

Guide to Setting Up Bootstrap 4 Beta Using Bower

Trying to update to the newest Bootstrap 4 Beta version via bower. Issue with this command: bower install bootstrap#v4.0.0-beta Getting the error message: no matches found: bootstrap#v4.0.0-beta Is there something incorrect in my process? This is how ...

Attempting to limit the user's input to only the beginning of the string

To prevent unexpected data from affecting the database and front end display, I am looking to limit users from inputting a negative sign at the beginning of their number only. My attempted solution so far: if(e .key Code == 109) { return ; } ...

Issue encountered: "ERROR TypeError: Upon attempting to patchValue in ngOnInit(), the property 'form' is undefined."

Can someone help me figure out how to use the patchValue method in the ngOnInit() function? I'm trying to populate a HTML select dropdown with a value from a link, but it's not working as expected. Note: onTest() works perfectly when called sepa ...

Utilize Function type while preserving generics

Is there a way in Typescript to reference a function type with generics without instantiating them, but rather passing them to be instantiated when the function is called? For instance, consider the following type: type FetchPageData<T> = (client : ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

Declarations for TypeScript in NPM packages

In order to streamline my development process with bun.sh using workspaces as npm packages, I have created a tool available here. However, I am facing two issues: After bun installing the 'core' packages from npm and testing a sample, I encounte ...

TypeScript raises an issue with a Vue component property that has been defined using vue-property-decorator

I have a Vue component with a property defined using a decorator: import { Component, Vue } from "vue-property-decorator" @Component({ props: { myId: String, }, }) class TestProp extends Vue { myFuncti ...

Guide on sending information through a POST request from Angular to a .Net API

My attempt to make a simple request is failing because the value(property) in API is null. Any suggestions on how to troubleshoot this? C# [Route("getpagefields")] [AcceptVerbs(WebRequestMethods.Http.Post)] public IHttpActionResult GetPageFields ...

Tips for inserting values into a string array using jQuery or Angular 7

I have a series of checkboxes with values obtained from a loop. Instead of pushing these values into an array, I need to join them together as "parent1", "parent2", "parent3" and display the result in the console. Below is the code snippet for reference: ...

Why is Selectpicker failing to display JSON data with vue js?

After running $('.selectpicker').selectpicker('refresh'); in the console, I noticed that it is loading. Where exactly should I insert this code? This is my HTML code: <form action="" class="form-inline" onsubmit="return false;" me ...

Disable the background color css when hovering over a button

I'm having trouble with my Angular and HTML code. https://i.stack.imgur.com/Ea5oV.png The image above shows that a background color appears when hovering over the first icon. I've attempted: .sidemenuitm { padding: 10px 5px; cursor: poin ...

What is the best way to handle parsing JSON with special characters in JavaScript?

Content stored in my database: "Recommended cutting conditions" When using Json_encode in PHP, the result is: {"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}; In JavaScript : var str ...

When should I schedule the execution of the .spec and .po.ts files in Protractor?

Curious about TypeScript and Protractor: I have a couple of basic helper functions stored in a shared.po.ts file within my Protractor suite. These functions are triggered by the third it() in my .spec file - meaning they are not immediately called upon ru ...

Dividing the text by its position value and adding it to a fresh object

I needed to divide the paragraph into sections based on its entityRanges. Here is what the original paragraph looks like: { type: 'paragraph', depth: 1, text: 'Do you have questions or comments and do you wish to contact ABC? P ...

Troubleshooting issues with sorting and pagination in Angular Material table functionality

I am experiencing an issue with sorting and pagination using an Angular material table. The data is being fetched from a store as an observable and successfully displayed in the table. Even though the column names for sorting match the column definitions, ...

Exploring data binding in Angular 2 through ngModelChange

When it comes to data binding, achieving property and event binding is possible with $event representing the entered value below: <input [ngModel]="username" (ngModelChange)="change($event)"> But what does the following code snippet mean? <inpu ...

FInding the inner value of a Vuetify chip

I have a Vue application that utilizes Vuetify chips to display information. I'm trying to log the value inside a specific chip when it is clicked, but I keep getting an undefined error when trying to access the array where the information comes from. ...