Retrieve data from a database using Angular

I am using Symfony as the Backend and Angular as the Frontend. I am attempting to showcase a list of all users from my postgresql database in a table. However, the browser only displays the information passed within the tags.

![display example](View post on imgur.com) https://i.sstatic.net/idcNk.png here is the eb_user.ts file where I declared the user

import {EbRole} from './role';

export class eb_user {
    id: number;
    nom: string;
    prenom: string;
    tel: string;
    mail: string;
    domaine: string;
    x_eb_role : string;


    constructor(){
        this.id = null;
        this.nom = '';
        this.prenom = '';
        this.tel = '';
        this.mail = '';
        this.domaine= null;
        this.x_eb_role = null;
    }

}

user.component.ts file:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription, from, BehaviorSubject } from 'rxjs';
import { CreateService } from 'src/app/services/create.service';
import { MatTableDataSource } from '@angular/material';
import {DataSource} from '@angular/cdk/collections';
import {Observable, of} from 'rxjs';
import 'rxjs';
import { eb_user } from 'src/app/classes/eb_user';
import { HttpClient } from '@angular/common/http';
import { Statique } from 'src/app/utils/Statique';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit, OnDestroy {

    private users: eb_user[];
    userSubscription: Subscription;

  constructor(private createService: CreateService,
              private http: HttpClient) {
       }

  getUsers() : void{
    this.createService.getUsers()
        .subscribe(users => this.users = users);
  }

  ngOnInit(){
    this.users = [];

  }

  ngOnDestroy(){
    console.log(this.users)
  }

}

users.component.html file:

<ul class="list-group"   style= "margin-top: 150px;">
  <li style="display: block;"><a routerLink="/create-user"> <button class="btn btn-primary">Create User</button></a></li><br>
</ul>

<table style="width: 100%;">
  <tr>
    <th> id</th>
    <th> nom</th>
    <th>prénom</th>
    <th>tel</th>
    <th>email</th>
    <th>domaine</th>
  </tr>
  <tr li class="list-group-item" *ngFor="let user of users">
    <td>{{user.id}}</td>
    <td>{{user.nom}}</td>
    <td>{{user.prenom}}</td>
    <td>{{user.tel}}</td>
    <td>{{user.mail}}</td>
    <td>{{user.domaine}}</td>
  </tr>
</table>

I anticipate that executing getUsers() will result in all registered users from the database being displayed.

Answer №1

Try removing the private keyword from the users declaration and it should start working.

Instead of:

private users: eb_user[];

Use this:

users: eb_user[];

Next, update your constructor as follows:

constructor(private createService: CreateService,
              private http: HttpClient) {
   this.getUsers();
}

Answer №2

Based on the code provided, the database will be queried for all users using the method:

getUsers();

However, this method is never actually called. It would be more practical to include the following code:

this.createService.getUsers()
        .subscribe(users => this.users = users);

in the constructor. This way, the data will be automatically fetched when the component is initialized.

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

Inject a cookie into the Axios interceptor for the request handler

I am in the process of setting up Axios to always include a request header Authorization with a value from the user's cookie. Here is my code: import axios, { AxiosRequestConfig, AxiosResponse} from 'axios'; import {useCookies} from "react-c ...

Step-by-step guide on transitioning code to utilize @use instead of @import

Currently, I am in the process of revamping a clubs app from Angular 9 to 18, as it has not been well maintained. My goal is to preserve as much of the frontend as possible and maintain the design more or less the same. Within the code, I have identified ...

Is there a way to implement a pipe function in TypeScript?

Introducing a unique pipe function implemented in plain JavaScript: const customPipe = (f, ...fs) => x => f === undefined ? x : customPipe(...fs)(f(x)) const exampleFunction = customPipe( x => x + 1, x => `wow ${x * 2} this is an amaz ...

Issue: Unable to locate control with the specified name

Having trouble submitting a reactive form with form arrays, I've searched through various solutions on different forums without success. It seems like I may be overlooking something obvious. The errors I'm encountering are "ERROR Error: Cannot fi ...

Angular application experiencing loading issues on Firefox caused by CSP problems

I am encountering an issue while trying to access my app on the testing server. The internal URL I am using is: . However, when I visit the page, it appears completely blank and upon inspecting the dev console, I see the following error message. This situa ...

Guide on how to use window.resize subscription in an Angular service?

I have been experimenting with the WindowService in my Angular project. Here is the code I have written: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; interface WindowSize { width?: number; height? ...

The View does not get updated by Angular's *ngFor directive

When I modify the Array of servers from outside the class declaration, the View/HTML component does not update accordingly. However, when I perform the same modification from inside the class, it works fine. Both functions successfully update the servers A ...

Experimenting with key directive in the newest version of Angular (9)

I'm currently testing a directive, but I am facing an issue where the length of the value in the directive is always undefined. What could be causing this problem? @Directive({ selector: '[evAutoTab]' }) export class EvAutoTabDirective { ...

The error "commands.reduce is not a function" is encountered when using the router.navigate function in

When I try to send a string as a link to my router, such as "/blog/pages/3", I encounter the error "commands.reduce is not a function". Surprisingly, despite the error message showing up in the console, the navigation still works. goToPage(link) { this ...

TypeScript encounters a problem when attempting to concatenate arrays with different signature overloads

I encountered the following error message: There is an issue with overloading. Overload 1 of 2, '(...items: ConcatArray<{ title: string; width: number; dataIndex: string; render: (level: string) => Element; }>[]): { title: string; width: nu ...

What is the correct way to install @angular-devkit/build-angular in Angular version 13?

In my Angular 13 project, I am facing a dilemma with conflicting dev dependencies: "devDependencies": { "@angular-devkit/build-angular": "~13.2.5", "@angular/cli": "~13.2.5", "@angular/co ...

Error: module not found in yarn

https://i.sstatic.net/3zEMq.png In my yarn workspace, I have organized folders named public and server. While working with TypeScript in VS Code, I encounter an error message stating: Cannot find module 'x' Interestingly, even though the error ...

Tips for obtaining response headers

Currently, I am utilizing Angular version 15.0 and retrieving a list of items from the backend (ASP.NET Core 5) with an additional item attached to the header. The GET method in the client-side service is as follows: /** GET Paged commodities from the s ...

The latest version of IntelliJ Idea Ultimate, 2023.2.5, does not offer compatibility with the updated control flow features in Angular

I recently made the switch to Angular 17 in my project and noticed that Idea is not recognizing the new syntax in HTML templates. <mat-menu #menu="matMenu"> @for (menuItem of getData().menu.items; track menuItem) { & ...

When using ngModel, the Tinymce Angular 2+ templates do not initially replace values, whereas they do when templates are inserted by the user

In my Angular 7 app, I am utilizing the TinyMCE editor component. When I insert a template variable into the editor: <span class="data-variable">${variable_name}</span> The variable gets replaced successfully with a value from the `template_r ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

Deploy your Angular website for absolutely no cost on Firebase by leveraging the Command Line Interface

Looking to deploy an Angular application on Firebase cloud for free using the CLI? Recently started delving into Angular 9 and exploring Firebase's cloud server capabilities, I'm interested in seeing how simple it is to deploy an app on Firebase. ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

Can you explain the mechanics behind the functionalities of @angular and @type dependencies?

This inquiry may have been raised before, but I couldn't uncover all the solutions. If that's the case, my apologies. I have a good grasp on how package.json and dependencies / dev-dependencies function in Node applications. Currently delving i ...

What steps should I take to retrieve my information from a typescript callback function?

While I am familiar with using callbacks in JavaScript, I have recently started learning Angular and TypeScript. I am facing an issue with getting my data from a service back to where I need it after executing the callback function. The callback itself i ...