Using an array of objects as a data source for the Material Angular table

My user data is causing some issues and looks like this...

[{"firstName":"Pinkie","lastName":"Connelly","username":"Darlene.Marvin","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19506a767b7c75464b7c77777c6b5971766d74787075377a7674">[email protected]</a>"},{"firstName":"Easter","lastName":"Ruecker","username":"Giovani.Collier59","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6a78888878b8783d3d2a6818b878f8ac885898b">[email protected]</a>"},{"firstName":"Harmon","lastName":"Luettgen","username":"Rosanna51","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b466478636e32334b726a63646425686466">[email protected]</a>"},{"firstName":"Angeline","lastName":"Kunze","username":"Gabriel_Braun69","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6923080a021a06075b582901061d04080005470a0604">[email protected]</a>"},{"firstName":"Gayle","lastName":"Bahringer","username":"Dorcas_Roob55","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ecab9e89959f8382d5daac8b818d8580c28f8381">[email protected]</a>"},{"firstName":"Adriana","lastName":"Renner","username":"Serenity.Armstrong42","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cd9ea4a0e39fa2afa8a18daaa0aca4a1e3aea2a0">[email protected]</a>"},{"firstName":"Arvid","lastName":"Kiehn","username":"Estrella87","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="246e455d48454a7b694b564d5757415050411314645d454c4b4b0a474b49">[email protected]</a>"},{"firstName":"Kristofer","lastName":"Nader","username":"Terence.Walker7","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abe9d9cacfd29292ebc3c4dfc6cac2c785c8c4c6">[email protected]</a>"},{"firstName":"Rosa","lastName":"Lebsack","username":"Freida_Hegmann46","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27664b464949467874444f4a4e53531f1e1e674f48534a464e4b0944484a">[email protected]</a>"},{"firstName":"Rogers","lastName":"Thiel","username":"Mike_Braun","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="18597f767d6b364b70717d747c6b2b587f75797174367b7775">[email protected]</a>"}]

I am using Angular and have imported Material Angular. Initially, I faced a challenge with using *NgFor with this data structure. But since Angular V6, you can now utilize a keyValue pipe which is quite convenient!

Next, I attempted to use *NgFor within a table to populate rows for each person. However, instead of NgFor, tables require the usage of dataSource:

<table mat-table #table [dataSource]="user">
  <!-- table rows -->
</table>

Nevertheless, I encountered an error stating:

Provided data source did not match an array, Observable, or DataSource at getTableUnknownDataSourceError

This is how I am fetching the user data -

export class AppComponent {
  error: any;
  title = 'toms-app';
  user: User;

constructor(private apiServicefile: ApiServicefile) { }


ngOnInit(): void {
  this.apiServicefile.getUser()
    .subscribe(
      (data: User) => this.user = { ...data }, // success path
      error => this.error = error // error path
    );
}
}

I am new to TypeScript and would appreciate some guidance on achieving my desired outcome. Can someone please assist?

Answer №1

this.data is not a List after:

{ ...info };

Simply update it like this:

this.data = info;

An alternate way to enhance it in HTML would be:

<table mat-table #table [dataSource]="data | async">
  <!-- table rows -->
</table>

In the TS file, your data should be:

List<Data>

, instead of just Data. When using the 'async' pipe in HTML, you can specify it as:

Observable<Array<Data>> or Observable<Data[]>

and then assign this.apiServicefile.getData() to this field.

export class AppComponent {
  error: any;
  title = 'toms-app';
  data: Observable<Array<Data>>;

  constructor(private apiServicefile: ApiServicefile) { }

  ngOnInit(): void {
    this.data = this.apiServicefile.getData();
  }
}

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

What is the process for obtaining a Component's ElementRef in order to access the BoundingClientRect of that specific Component?

I have successfully created a tooltip using Angular 5.2.0 and ngrx. The tooltip, among other things, receives an ElementRef to the target Element when the state updates, allowing me to position it absolutely: let rect = state.tooltip.target.nativeElement. ...

Swapping elements with drag and drop in Angular 7

I'm experimenting with the new Angular 7 CDK Drag and drop feature to rearrange a list of items. However, I haven't been able to find an option to swap elements - most of the examples focus on sorting elements instead. Check out this example on ...

Shifting attention to an angular 6 form field

I am developing an application in Angular which involves creating, reading, updating, and deleting user information. I have a requirement for the username to be unique and need to display an error message if it is not unique, while also focusing on the use ...

Executing a designated assessment in Protractor

Is there a way to run a specific test scenario in my Angular app? I recently added a new feature in Protractor, created the necessary page and steps, but I already have other features implemented. I am wondering if it is possible to solely test the new f ...

Struggling to determine data type in Typescript

My goal is to create an interface for my realm Database using TypeScript. Essentially, I have an automation bot and I want to monitor and track how users are utilizing it. To achieve this, I have designed specific schemas that will be integrated into an i ...

transmit URL parameters to Express using Angular 2

I have implemented an Angular service to retrieve data from Express: getRestaurants(districtId) : Observable<void[]>{ let params: URLSearchParams = new URLSearchParams(); params.set('id', districtId); return this.http.get(this.url, ...

Using async method in controller with NestJS Interceptor

I am seeking a way to capture both the result and any potential errors from an asynchronous method within a controller using an interceptor. When an error is thrown, the interceptor can respond accordingly. However, I am struggling to figure out how to tri ...

Showing or hiding elements based on user roles in Angular 4

I am currently working on a project that involves multiple user types (SuperUser - SchoolAdmin - Teacher). Each role has specific privileges to access certain elements. How can I dynamically hide elements based on the logged-in user's role using *ng ...

Guide to populating a dropdown list using an array in TypeScript

I'm working on a project where I have a dropdown menu in my HTML file and an array of objects in my TypeScript file that I am fetching from an API. What is the best approach for populating the dropdown with the data from the array? ...

Implementing atomic design principles in Vue 3 with TypeScript

I'm currently implementing atomic design principles in my Vue application. Here is the code for my button atom: <template> <ElButton :type="button?.type" :plain="button?.plain" :rounded="button?.rounded ...

Mat-dialog not filtering JSON data properly due to filter buttons not combining logic

I'm currently working on developing a filter component, and I've encountered an issue. When I select both Buy it Now and Private Auction options, they function independently but not together. If an item has both Buy It Now and Private Auction ena ...

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...

Is the Inline Partial<T> object still throwing errors about a missing field?

I recently updated to TypeScript version ~3.1.6 and defined an interface called Shop as follows: export interface Shop { readonly displayName: string; name: string; city: string; } In this interface, the property displayName is set by the backend a ...

Tips for preserving @typedef during the TypeScript to JavaScript transpilation process

I have a block of TypeScript code as shown below: /** * @typedef Foo * @type {Object} * @property {string} id */ type Foo = { id: string } /** * bar * @returns {Foo} */ function bar(): Foo { const foo:Foo = {id: 'foo'} return f ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

The Angular HTTP request is coming back with a status of 0, even though I was anticipating

I need to access a server with various routes. The routes are as follows: app.use('/401', (req, res) => res.status(401).end()); app.use('/403', (req, res) => res.status(403).end()); app.use('/404', (req, res) => res. ...

Having trouble simulating a custom Axios Class in JavaScript/TypeScript

Here are the function snippets that I need to test using jest, but they require mocking axios. My attempt at doing this is shown below: // TODO - mock axios class instance for skipped Test suites describe("dateFilters()", () => { beforeEac ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

Using React hooks with Material-UI: Snackbar displaying only on first occasion and not again

I have identified an issue that can be easily reproduced. Steps to replicate: Step 1: Start a react app and include material-ui in the project: prompt> create-react-app mui-test prompt> cd mui-test prompt> yarn add @material-ui/core @material-ui ...