Component in Angular does not display the list of employees

Having some trouble displaying registered employees in my Angular app. It seems that the values are not appearing, only their array items are being created. I checked with a console.log and it looks like the variables are undefined. Any assistance would be appreciated.

employee.component.html

<div class="row animated fadeIn">
  <div class="col-12">
      <div class="card">
          <div class="card-body">
              <h3 class="card-title"> Registered Employees </h3>

              <table class="table table-hover" >
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Code</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th></th>  
                  </tr>
                </thead>
                <tbody>
                  <tr *ngFor="let employee of employees">
                    <td>{{employee.name}}</td>
                    <td>{{employee.code}}</td>
                    <td>{{employee.position}}</td>
                    <td>{{employee.office}}</td>
                    <td>
                      <button class="btn btn-primary"> <i class="fa fa-save"></i></button>
                      <button class="btn btn-danger"> <i class="fa fa-trash-o"></i></button>
                    </td>
                  </tr>
                </tbody>
              </table>

          </div>
      </div>
  </div>
</div>

employee.component.ts

    import { Component, OnInit } from '@angular/core';
import { Employee } from '../models/employee.model';
import { EmployeeService } from '../services/employee.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {

  employees: any[] = [];

  constructor(public employeeServ: EmployeeService) { }

  ngOnInit() {
    this.retrieveEmployees();
    console.log(this.employees.length);
  }

  retrieveEmployees() {
    this.employeeServ.getEmployees()
        .subscribe( (resp: any) => {
          console.log(resp[0].name);

            for (let index = 0; index < resp.length; index++) {
              this.employees[index] = resp[index];
              console.log(this.employees[index]);
            }
            // JSON.stringify(this.employees);
            console.log(this.employees[0].name);
        });

  }

}

employee.service.ts

    import { Injectable } from '@angular/core';
import { Employee } from '../models/employee.model';

import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError  } from 'rxjs/operators';


import swal from 'sweetalert';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(public http: HttpClient) { }

  saveEmployee(employee: Employee): Observable<any> {
      return this.http.post('http://localhost:62200/api/Employee', employee)
                 .pipe(
                   map( (resp: any) => {
                    swal('Employee created', employee.name, 'success');
                    return employee;
                   }),
                   catchError((e: any) => throwError(e))
                 );
  }


  getEmployees()  {
    return this.http.get('http://localhost:62200/api/Employee');
  }

  deleteEmployee(id: number): Observable <any> {
    return this.http.delete('http://localhost:62200/api/Employee/' + id)
                 .pipe(
                   map( (resp: any) => {
                    swal('Employee deleted', 'Deleted', 'warning');
                    return resp;
                   }),
                   catchError((e: any) => throwError(e))
                 );
  }

}

When attempting to display the employees, the items are created but the name, code, position, and office details don't appear.

https://i.sstatic.net/NZoNU.png

Answer №1

It's important to remember that properties are case sensitive.

For instance, make sure to change empleado.nombre to empleado.Nombre

 <tr *ngFor="let empleado of empleados">
                    <td>{{empleado.Nombre}}</td>
                    <td>{{empleado.Codigo}}</td>
                    <td>{{empleado.Posicion}}</td>
                    <td>{{empleado.Oficina}}</td>
                    <td>
                      <button class="btn btn-primary"> <i class="fa fa-save"></i></button>
                      <button class="btn btn-danger"> <i class="fa fa-trash-o"></i></button>
                    </td>
                  </tr>

Answer №2

It appears that there is a discrepancy between the lowercase property names in your markup and the uppercase property names of the data objects returned from the server.

                <td>{{empleado.nombre}}</td>
                <td>{{empleado.codigo}}</td>
                <td>{{empleado.posicion}}</td>
                <td>{{empleado.oficina}}</td>

To fix this issue, try using the uppercase property names in your markup instead (empleado.Nombre, etc.). That should resolve the problem.

Answer №3

Why are you showing alert messages in the Service? This should be done in the Component.

If console.log() in the service is returning results, try using the code snippet below.

Component:

fetchEmployees() {
    this.employeeService.getEmployees()
        .subscribe((response: any) => {
          this.employees = response;
        });
  }

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

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

Leveraging Angular App with the Bootstrap .modal() JQuery method

I'm encountering issues with Bootstrap 4 and NPM/Angular CLI when using the .modal methods Error: TypeError: $(...).modal is not a function Main.ts: import * as $ from 'jquery'; import * as bootstrap from 'bootstrap'; App.compo ...

Ways to resolve issue: TypeError - req.url.toLowerCase is not a function

I am in the process of setting up a new service and I plan on using mock data from a JSON file to get started. However, I encountered an error saying TypeError: req.url.toLowerCase is not a function when testing the service with the mock data. How can I tr ...

Ways to retrieve specific Observable elements?

Having a function like this: getCategories(): Observable<any> { return this.category.find({where: {clientId: this.userApi.getCurrentId()}}) }; The return type of this.category.find is Observable<T[]>. When I invoke g ...

Is there a way to detect changes in a Service variable within an Angular component?

One of my components contains a button that activates the showSummary() function when clicked, which then calls a service named Appraisal-summary.service.ts that includes a method called calc(). showSummary(appraisal) { this.summaryService.calc(appraisal ...

Exploring the functionality of Kendo Grid within an Angular application

Currently, I am facing some challenges while trying to execute my Karma tests using the kendo grid within a fresh Angular project. The specifications for this specific component are outlined below: import { async, ComponentFixture, TestBed } from '@a ...

Exploring the HashLocationStrategy feature in Angular 18

Looking to integrate HashLocationStrategy in Angular 18, but facing the challenge of not having an App Module in this version ...

The error message displayed by Create React App states: "You cannot utilize JSX without the '--jsx' flag."

I need help with overcoming this particular issue in a TypeScript based React application: Encountering an error stating "Cannot use JSX unless the '--jsx' flag is provided" ...

Transmit information from an Angular2 Component to node.js

Ready to send a string value to my node server and locate it in MySQL table. A component is receiving data from a service ngOnInit() { this.instructionsService.getAllInstructions().subscribe(instructions => { this.instructions = instructions ...

Using Angular's CanDeactivateGuard with Child Components in Angular4

Ensuring user awareness of unsaved changes when navigating away from a page is crucial. Previously, I achieved this in angular 1 using the ng-unsaved changes plugin. However, in angular 4, it seems recommended to utilize the canDeactivate feature. This wor ...

Implementing shared element route transitions using framer-motion and NextJS (written in typescript)

I'm having trouble implementing animated routing using the <AnimateSharedLayout /> component from framer-motion. What I'm trying to achieve in the code below is to show a list of images and, upon clicking on them, navigate to /images/[image ...

Trigger change event on model update in Angular 4 checkboxes

CSS <div class="checkbox-item"> <input type="checkbox" id="1" [(ngModel)]="filter" (change)="onFilterChange($event)"> CheckBox </div> <button (click)="filter = !filter">Change Status</button> JavaScript export class Filt ...

What is the best way to arrange a list in Angular2 using AngularFire2's FirebaseListObservable?

Looking to retrieve all users from a Firebase realtime database and organize them based on a score property. I managed to achieve this by using the variable users: FirebaseListObservable<any[]>; however, encountered the following errors: Type & ...

Angular 6 and Bootstrap 4 Collaborate for a Dynamic Multi-Level NavBar

(UPDATE: Issue Resolved - I discovered that I needed to include the JavaScript within $(document).ready(function()), which was previously missing. The example below worked perfectly for me.) I am attempting to implement a Multi-Level Navbar with Angular 6 ...

How to assign attributes to all child elements in Angular?

I have a unique component in Angular that I utilize throughout my app. It's a button component which I use by calling <app-delete-btn></app-delete-btn> wherever needed. I tried to set the tabindex="1" attribute for my component ...

Resolving conflicts between class names for React-Icons in Typescript and Javascript (Answering my

After working with React in JavaScript, I made the switch to NextJs with TypeScript. I encountered an issue when trying to import react-icons such as BiUser. In React, adding a className to icons worked smoothly, but in TypeScript, it resulted in an error ...

The parameter does not accept a string as an argument, it only allows for values of "one", "two", "three", "four", "five", or "six"

I'm facing a challenge with my specific type: type OtpCode = { one: string; two: string; three: string; four: string; five: string; six: string; }; I want to iterate through this object and assign values: Object.keys(defaultValues).forEac ...

What is the best way to refresh a Load on Demand feature in Nativescript?

In my RadListView, the data displayed changes depending on the day selected by the user in a calendar. Currently, I am using loadOnDemandMode = "Manual" and it functions smoothly until all the available data is loaded. At that point, I trigger listView.no ...

Displaying Angular ng-repeat Key Value

I am trying to figure out how to display the key in the products AL200W401 (without xxxx) using ng-repeat. Currently, my HTML code is displaying the AL200W401xxxx key instead. Any advice on how to achieve this? Thank you. JSON { "kits":"B11D0W201, ...

Using Angular 2 for form validation

Hey there, I'm currently using Angular 2 and I need to set the password field requirements to include at least 1 uppercase letter, 1 lowercase letter, 1 number, 1 special character with a minimum of 8 characters and maximum of 16 characters. So far, ...