Mastering the art of implementing md-table with services in Angular 4

I am a newcomer to the world of angular and I am attempting to utilize the new md-table component in Angular Material 2 with Angular 4.

I have created a service that fetches simple arrays of content from an API. However, I am struggling to use this service as a data source for the md-table as I am unable to retrieve the data from the service (it always returns an empty array).

Prior to using md-table, I had successfully used the service without any issues.

Below is the code for the component :

// Component code here
...

Here is the corresponding HTML code :

// HTML code here
...

And here is the service code :

// Service code here
...

I am unsure about the correct way to call the service using the datasource. I have tried calling it in the ngOnInit method as I did previously, but it does not seem to work. Any help would be greatly appreciated.

Thank you for your assistance.

Answer №1

Check out this demonstration of retrieving data using HTTP: https://plnkr.co/edit/mjQbufh7cUynD6qhF5Ap?p=preview


There is an issue with the GroupDatabase where it is not populating the dataChange stream with any data values. The BehaviorSubject starts with an empty array but remains empty as no additional data is added to it. This is why the table is only displaying an empty array.

Keep in mind that Angular will not trigger the ngOnInit lifecycle hook since GroupDatabase is not a directive and does not participate in the change detection process.

Instead of calling this.getAllGroups() in ngOnInit, it is recommended to move it to the constructor of GroupDatabase and subscribe to its result:

export class GroupDatabase {
  public dataChange: BehaviorSubject<Group[]> = new BehaviorSubject<Group[]>([]);
  get data(): Group[] { return this.dataChange.value }

  constructor(groupService: GroupService) {
    groupService.getAllGroups().subscribe(data => this.dataChange.next(data));
  }
}

Alternatively, you can eliminate the usage of GroupDatabase and have your CustomDataSource directly interact with your GroupService.

export class CustomDataSource extends DataSource<Group> {

  constructor(
      private _groupService: GroupService, 
      private _paginator: MdPaginator) { }

  connect(): Observable<Group[]> {
    const displayDataChanges = [
      this._groupService.getAllGroups(),
      this._paginator.page
    ];

    return Observable.merge(...displayDataChanges).map((data, page) => {
      const clonedData = data.slice();

      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      return data.splice(startIndex, this._paginator.pageSize);
    })
  }

  disconnect() {}
}

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 best way to incorporate infinite scrolling into my Angular carousel implementation?

After following an amazing tutorial, I was able to create a basic carousel using two directives and one component in Angular. However, the current version of the carousel lacks an 'infinite scrolling' mode, which is something I would like to inc ...

The attribute 'id' cannot be found in the class 'Foods'

After examining my code below, I am attempting to remove clients from my data table by using checkboxes. Whenever I check a checkbox, I notice in the console that the object's properties are retrieved from the database. My goal is to delete by id, but ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

The function `Object.entries().map()` in TypeScript does not retain the original data types. What changes can I make to my interface to ensure it works correctly, or is there a workaround

Working with this interface: export interface NPMPackage { name: string; description: string; 'dist-tags': { [tag: string]: string; }; versions: { [version: string]: { name: string; version: string; dependencie ...

When using string as a primitive type in Vue 3, what distinguishes the usage of PropType in props from not using it?

The documentation explains how Vue does runtime validation on props with defined types. To enable TypeScript to recognize these types, constructors are cast with PropType. The code example in the documentation uses success: { type: String }, whereas it c ...

Can we modify the styling of elements in Angular based on an object property?

I have a class named Task with the following properties: export class Task { name: string; state: number; } Within my component.ts file, I have an array of objects consisting of instances of the Task class (tasks). When displaying them in the tem ...

Using *ngIf with values from an array in *ngFor in Angular 2: How to make it work?

i just started learning angular 2 and ionic, so I'll keep it brief: <ion-card class="acc-page-card" *ngFor="let account of accounts"> <ion-card-content> <!-- Add card content here! --> <ion-item (click)="GoTo('Ac ...

Display a symbol retrieved from the backend server

After receiving a response from the backend server for my Angular 2/4 application, I am presented with an attribute called "connectionStatus". This attribute indicates the status of a database connection, either as "UP" or "DOWN". In order to display this ...

Leveraging the data set offered by Service and Interface in Angular to display specific data in Component

After creating an Interface and Service for my test data, let's take a look at the code: interface.ts export interface IColumn { label: string; value: string; } export interface IRecords { Lp: string; id: string; pluginName: string; port ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...

Trouble accessing images from database in Angular 2 with Firebase

Recently, I've integrated an image upload feature for my database using the following function: private saveFileData(upload: Upload): void { this.firebaseAuth.authState.subscribe(auth => { this.db.list(`uploads/${auth && auth.email && au ...

Using ngx-bootstrap typeahead with custom itemTemplate for objects

I've created a custom ngx-bootstrap/typeahead component for my ngx-formly generated forms. This component fetches search results from an API and is designed to be reusable for various objects, making it dynamic. My goal is to have the typeahead retri ...

The component 'Form' cannot be utilized in JSX because its return type, 'ReactNode', is not a valid JSX element

I'm facing an issue with my Next.js application written in TypeScript after updating react-bootstrap. After the update, I am encountering the following error when attempting to use the Form component from react-bootstrap: react-bootstrap: ^2.10.3 @typ ...

The appearance of the Angular app undergoes a change following deployment using ng build

I have been working with Angular for several years now, but only recently delved into using Angular Material components in my latest project. I was pleased with how my layout turned out and ready to push it to production. However, after deployment, the com ...

The automatic inference of function argument types and the implementation of conditional types

I'm facing a specific scenario: There's a function that takes in a boolean and returns either a RealItem or an ImaginaryItem. I'm using conditional types to determine the return type based on the boolean argument. type RealItem = { color: s ...

Angular2 - The Iterable Differ fails to detect changes

I am currently utilizing the Iterable Differs feature in Angular2 to monitor changes in my data. However, I am facing an issue where the differ.diff method always returns "null" and I am unsure of the reason behind this. constructor(differs: IterableDiffe ...

Having troubles with *ngFor in Angular 8? Learn how to use ng-template effectively

I need assistance creating a table with dynamically generated columns and using the PrimeNg library for the grid. Despite asking several questions, I have not received any responses. Can someone please help me achieve this? To generate table column heade ...

Is there a tool in Node.js to set up a new project, similar to the scaffolding feature in Visual Studio for C# projects

Is there a way to efficiently create a node.js project with TypeScript and Express, and embed an SPA client using React and Redux templates written in TypeScript as well? Is there a scaffolding tool available to streamline this process, similar to the ea ...

Aligning two identical components within the same container when triggered by a single click

Currently, I am exploring Angular 2 and Typescript and have been developing a pager component for a table. The pager functions correctly, but I have encountered an issue with having two pagers - one above the table and one below it. When the next button on ...

What is the best way to incorporate a 'category filter' in Angular2?

Unique Scenario In my Angular2 application, I have implemented code in a component's view parent.component.html that iterates through an array of items and generates a new component for each item: <div class="list-items"> <!-- The colored ...