Issue in Angular: Material Table not displaying data even though no error is detected

I've checked my console for errors, but I'm still unable to display it in the Material Data Table. I've been reviewing the code for some time now, but I can't seem to figure out what's wrong. The only thing that comes to mind is that the API may not be correct. The xxxxx stands for a URL of an API. Unfortunately, I cannot reveal the actual link.

restaurant.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Restaurant } from '../models/restaurant.model';

@Injectable({
  providedIn: 'root'
})
export class RestaurantService {
  private restaurantsUrl = 'https://xxxxxx/getAllServices.php';

  constructor(private http: HttpClient) { }

  getRestaurants(): Observable<Restaurant[]> {
    return this.http.get<Restaurant[]>(this.restaurantsUrl);
  }
}

restaurant-table.component.ts

import { Component, ViewChild,OnInit } from '@angular/core';
import { RestaurantService } from '../services/restaurant.service';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import {DataSource} from '@angular/cdk/collections';
import { Restaurant } from '../models/restaurant.model';


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

export class RestaurantsTableComponent implements OnInit {

  dataSource = new RestaurantDataSource(this.restaurantService);
  displayedColumns = ['id', 'ime_restorana', 'opis', 'broj_telefona', 'adresa_restorana','edits'];

  constructor(private restaurantService: RestaurantService) {
}

  ngOnInit() {
  }

}

export class RestaurantDataSource extends DataSource<any> {

  constructor(private restaurantService: RestaurantService) {
    super();
  }

  connect(): Observable<Restaurant[]> {
    return this.restaurantService.getRestaurants();
  }

  disconnect() {}

}

restaurant-table.component.html

<div class="">
  <mat-table [dataSource]="dataSource">

    <ng-container matColumnDef="id">
      <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
      <mat-cell *matCellDef="let restaurant"> {{ restaurant.id }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="ime_restorana">
      <mat-header-cell *matHeaderCellDef> Naziv </mat-header-cell>
      <mat-cell *matCellDef="let restaurant"> {{ restaurant.ime_restorana }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="opis">
      <mat-header-cell *matHeaderCellDef> Opis </mat-header-cell>
      <mat-cell *matCellDef="let restaurant"> {{ restaurant.opis }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="broj_telefona">
      <mat-header-cell *matHeaderCellDef> Broj Telefona </mat-header-cell>
      <mat-cell *matCellDef="let restaurant"> {{ restaurant.broj_telefona }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="adresa_restorana">
      <mat-header-cell *matHeaderCellDef> Adresa </mat-header-cell>
      <mat-cell *matCellDef="let restaurant"> {{ restaurant.adresa_restorana }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="edits">
      <th mat-header-cell *matHeaderCellDef></th>   
      <td mat-cell *matCellDef="let element"> 
        <button mat-raised-button class="edit-btn"><mat-icon>edit</mat-icon></button> 
        <button mat-raised-button class="edit-btn"><mat-icon>remove_red_eye</mat-icon></button> 
      </td>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>

  </mat-table>
</div>

User.model.ts

export interface User {
    name: string;
    email: string;
    phone: string;
    company: {
        name: string;
    }
}

Answer №1

Your current dataSource is currently set as an instance of the RestaurantDataSource class. What you actually need is the real list of restaurants. So, you should do this:

dataSource = new RestaurantDataSource(this.restaurantService).connect();

But here's the catch - your connect() method gives back an Observable, not the actual list. To handle this, make sure to use the async pipe in your template like so:

<mat-table [dataSource]="dataSource | async">

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 could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

"Implementing jQuery to dynamically set the href attribute for a link when

My website features a tabbed menu that displays content from various WordPress categories including Cars, Trucks, and Buses. The active tab is randomly selected each time the page is reloaded. However, there seems to be an issue with the "View More" button ...

webpack is encountering difficulty resolving the node_modules material-icons directory

Encountering an Error ERROR in ./node_modules/material-icons/iconfont/material-icons.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_mod ...

Change JSON to an unordered list using <ul> and <li

I came across an item that resembles the following: { "qA": [ { "question": "How deep is the ocean", "answer": [ "quite deep", "very deep", "no deep at all" ] ...

Is there a way to enhance the search feature by incorporating a for loop to iterate through data.games and display the corresponding score when a search is made?

$(document).ready(function(){ var searchTerm = "XYZ"; var totalScores = 0; $.ajax({ dataType: 'jsonp', //data in jsonp contentType: "application/json; charset=utf-8", url: 'http://live.nhle.c ...

What is the best approach for retrieving Google API responses - accessing them directly from the frontend or routing through the backend first?

Currently, I am in search of the optimal location to make Google API requests. Given that Google Maps is utilized in the front end, we have the option to directly call the distance API service from there. However, we also have the choice to access these se ...

Tips for retrieving a JSON object value using a key in Angular 6 View

As a beginner in Angular 6, I am struggling to figure out how to access values from a JSON object in the view using keys. In my service, I am making an http.get(url) call and then invoking that method in my component. export class CustomersComponent impl ...

strange issue encountered while utilizing JavaScript's async/await syntax

Recently, I encountered an issue while trying to retrieve a random user from the randomuser API using code in my Vue frontend. // Here is the structure of the API response { info: { // details omitted }, results: [ {//random user data} ] } // This snippet ...

Transmitting form data inputted by the user to a modal that resides in the same component, all without the need for child or parent components or

In need of a solution where users can input answers to questions and have all the entered data displayed in a popup alongside the respective question. If a user chooses not to answer a question, I do not want that question or any related information to be ...

Reordering a pair of items within an array using ReactJS

After pondering, I wondered if there exists a neat and tidy method to swap two objects within an array while utilizing setState. Here's my current approach: export function moveStepUp(index) { if(index > 0){ let currentStep = this.stat ...

Exploring the concept of unprojection in three.js

Check out this jsfiddle example of what I am trying to achieve - seeing a 3D object drawn exactly behind the cursor as it moves across the screen. http://jsfiddle.net/ksRyQ/3551/ unp = p.unprojectVector(new THREE.Vector3( mx - (window.innerWidth/2), (wi ...

The web application I developed has a glitch where it duplicates user input when creating a new post, and doesn't display the user's deleted

I've created a small Javascript app that serves as a to-do list. The frontend is built in basic Javascript, fetching data from an array and allowing users to add items to the list through post requests. The intended functionality includes the ability ...

Unit Testing with Angular: Testing the setValueControl function

I am currently in the process of writing unit tests for a straightforward function that assigns controls to various values. fillFormAssociazioneVeicolo() { if (this.aaa) { setValueControl( this.aaa.targaTelaio, this.form.get(&apos ...

Extracting data from a JQGrid in HTML5 Builder: a beginner's guide

Apologies for asking this question as I couldn't find any relevant posts addressing it specifically in relation to HTML5 builder. I am trying to retrieve the value of the "ID" column, which happens to be the last column among the four, based on the r ...

Check for the presence of a file in the directory and if it exists, load

Attempting to explain this query may lead to confusion. I have been searching for an answer for approximately three days with no success. It appears that the task at hand is either impossible or so straightforward that no one has encountered the need to in ...

"Unlocking the Dialog Box: A Step-by-Step Guide to Programatically Opening Material UI Dialog

Typically, Material UI's Dialog is used as shown below, following the documentation: export default function AlertDialog() { const [open, setOpen] = React.useState(false); const handleClickOpen = () => setOpen(true); const handleClose = () =& ...

What is the best way to split a semicircular border radius in two equal parts?

Is there a way to halve the yellow line or remove it from above the red box, while keeping it below? Can this be achieved using just HTML and CSS, or is JavaScript necessary? * { margin: 0; padding: 0; box-sizing: border-box; } body { height: 1 ...

Unable to display image using EJS and Multer

While working on my node.js application, I encountered an issue with rendering the uploaded image file. I have successfully integrated multer to handle file uploads, and the images are being stored in the correct folder. However, when trying to display the ...

Integrate Typescript compilation into the build process of Visual Studio 2017

I am currently working in VS2017 on a WebSite project where I have recently added a tsconfig.json file. I am wondering how I can automate the process of generating js files from ts files during the build phase? Interestingly, when I remove the tsconfig.js ...

HTML various button designs - such as a cogwheel

I need a button on my Angular/Electron project that resembles a gear icon. I came across these resources: here and here. However, when I tried to implement them, they didn't work as expected. Currently, the button looks like this: <button class= ...