The Angular HTTP GET request is failing to function properly as expected

I am currently working on developing the front end for an API request. The structure of the response model is as follows:

export class User {
    ID: number;
    first_name: string;
    last_name: string;
    isAdmin: boolean;
}

Within the user.components file, I have implemented the following code snippet:

 users: User[];

 ngOnInit(){        
        this.userService.getUsers().subscribe(data => {
                console.log(data);
                this.users = data;
            });
    }

As for the service:

   getUsers(): Observable<User[]>{
        return this.http.get<User[]>(this.apiUrl+"/users");

In the HTML template:

<table>
  <tr *ngFor="let user of users">
    <td>{{user.ID}}</td>
    <td>{{user.first_name}}</td>
    <td>{{user.last_name}}</td>
    <td>{{user.isAdmin}}</td>
  </tr>
</table>

When checking the console output, I received a Console log.

Although no errors are being displayed and the results are visible in the console, they are not appearing on the actual web page. After some experimentation, it seems that using the same variable names in the "User" class as in the backend resolves this issue. Is this expected behavior or am I overlooking something?

Answer №1

If you are looking to structure the received data according to a specific object format, Typescript interfaces are more suitable than classes. Interfaces are only accessible at compile time and can verify if the received data matches the expected type.

export interface User {
  user_ID: number;
  first_name: string;
  last_name?: string;
  isAdmin?: boolean;
}

It is crucial to ensure that the object structure from the backend aligns with a predetermined type. In your case, the ID is labeled as user_ID, so you must either update it in the frontend to match or modify it in the backend to ID. The object properties should precisely correspond between the backend and frontend, although optional properties can be defined.

export interface User {
  user_ID: number;
  first_name: string;
  last_name?: string;
  isAdmin?: boolean;
}

In this scenario, last_name and isAdmin properties are considered optional. Hence, both of these assignments are acceptable:

obj1: User = { user_ID: 1, first_name: 'sample' };
obj2: User = { user_ID: 1, first_name: 'sample', last_name: 'sample' };

Classes are typically utilized for data manipulation and computational tasks. They require instantiation similar to other OOP-based classes.

To summarize, TS interfaces and classes serve for type checks and introduce traditional OOP practices into Javascript. In principle, no specific type declaration is necessary when retrieving data from the backend. Thus, a simple approach could be like:

Services

getUsers(): Observable<any> {
  return this.http.get(this.apiUrl+"/users");
}

Component

users: any;

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

Angular 12: An issue has occurred due to a TypeError where properties of undefined cannot be read, specifically pertaining to the element's 'nativeElement

Within my phone number input field, I have integrated a prefixes dropdown. Below is the code snippet for this feature. HTML code in modal <div class="phone" [ngClass]="{ 'error_border': submitted && f.phoneNumber.er ...

Inheritance in Angular with TypeScript Using Generic Types

Looking for some assistance from the angular2 / typescript experts out there to guide me in the right direction before I lose my mind :-) Here's what I'm trying to achieve: I want to create a parent class that implements its own defined parent ...

Having trouble getting the Bootstrap 5 Modal to function properly within an Electron app

Facing an issue with my web app using Bootstrap 5, as the modal is not displaying properly. Below is the HTML code for the modal and the button that triggers it: <div class="modal" tabindex="-1" id=&quo ...

Filtering an array of objects based on a specific condition in TypeScript

I am trying to filter the array object data where the count of Failed is greater than 0. Unfortunately, the code below is not working as expected. ngOnInit() { this.employeeService.getProducts().subscribe((data:any) => { console.log(data); this. ...

Tips for cycling through a template for a component in Angular

My goal is to create a basic chess application using Angular. I have developed two components, Piece and Player, with each player having an array of 16 pieces (player1 and player2). The Piece component includes a template: <app-piece>. Now, I want t ...

Spread an all-encompassing category across a collection

What is the method in TypeScript to "spread" a generic type across a union? type Box<T> = { content: T }; type Boxes<string | number> = Box<string> | Box<number>; (Given that we are aware of when to use Boxes versus Box) ...

Angular: display many components with a click event

I'm trying to avoid rendering a new component or navigating to a different route, that's not what I want to do. Using a single variable with *ngIf to control component rendering isn't feasible because I can't predict how many variables ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

I find that in atom autocomplete-plus, suggestions take precedence over my own snippet prefix/trigger

I created my own custom code snippet for logging in a .source.ts file: '.source.ts': 'console.log()': 'prefix': 'log' 'body': 'console.log($1);' I use this snippet frequently and it sh ...

Navigating to the homepage in Angular 4 using routing

Below are the specified routes: const appRoutes: Routes = [ { path: 'signup', component: SignupComponent }, { path: 'home', component: HomeComponent }, { path: '**', component: HomeComponent } ]; Upon accessing www.my ...

TypeScript error: Attempting to assign a value to this.x within the class constructor is not allowed

interface ClassInterface { panelWidth: number; panelHeight: number; }; class Panels<ClassInterface> { constructor(panelWidth: number, panelHeight: number) { console.log(panelWidth); // 820 console.log(panelHeight); // 62 ...

Tips on creating type definitions for CSS modules in Parcel?

As someone who is brand new to Parcel, I have a question that may seem naive. In my project, I am using typescript, react, less, and parcel. I am encountering an error with typescript stating 'Cannot find module 'xxx' or its corresponding t ...

Error: The Angular service is throwing a ReferenceError because it is unable to find the definition

Within my Angular service, I have implemented the AudioContext as shown below: @Injectable({ providedIn: 'root' }) export class AudioService { private context = new AudioContext(); ... } During compilation, Angular presents the follow ...

The initial load of Angular OpenId Connect triggers the rendering process before the token is fully prepared

I am currently utilizing Angular 10 along with angular-auth-oidc-client (https://github.com/damienbod/angular-auth-oidc-client). My objective is to automatically redirect the user to the authentication server if they are not logged in without displaying a ...

What is the best way to implement pipes and incorporate reusable action buttons in a Mat-table component for maximum reusability?

I am seeking assistance in creating a reusable component for the Angular Material Mat-table. I have made progress on loading data from the parent component to the child component, as can be seen in StackBlitz, but I now want to apply pipes to the data bef ...

Jenkins build fails to copy Angular 4 assets during creation of build

Currently, I am working on building an Angular 4 project using Jenkins and then deploying the build onto an FTP server. Below is the command that I am executing: npm install && npm run dev I have defined "dev" in the package.json file as follows: "dev" ...

Configure NODE_OPTIONS to set the maximum old space size for an Angular application to Nx

In my Angular application within an Nx workspace, I am utilizing the @nx/angular:webpack-browser executor for building. "build": { "executor": "@nx/angular:webpack-browser", ... } This is a sizable application that necessita ...

In Typescript, mismatched index types do not result in errors being thrown

Why doesn't TypeScript raise an error or warning in the following code snippet? In the index type for map["xx"], it is specified as string, but in the map signature it's defined as number. Should any configuration be set in tsconfig to address th ...

WebSocket connection outbound from Docker container fails to establish

Running a TypeScript program on Docker that needs to open a Websocket connection to an external server can be a bit tricky. Here is the scenario: ----------------------- ------------------------------ | My Local Docker | ...

Unique text: "Singleton React component"

A counter component has been implemented using a npm package available here. import * as React from 'react'; import { Theme, createStyles, withStyles, WithStyles } from '@material-ui/core'; import withRoot from '../../../withRoot&a ...