'I'm trying to do a http get request to get data from my backend Larval, MYSQL I have created the API in Laravel but cant display the data in Angular

I'm new to programming and new advise please here is my code

employees component

import { DataService } from './../../service/data.service';

import { Component, OnInit } from '@angular/core';

@Component({

selector: 'app-employees',

templateUrl: './employees.component.html',

styleUrls: ['./employees.component.css'

]})

export class EmployeesComponent implements OnInit {

employees: any

constructor(private dataservice: DataService) { }

ngOnInit() {
}
getEmployeesData() {
    this.dataservice.getData().subscribe((res: any) => {
        this.employees = res;
    });
}

}

data.service.ts

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

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

getData: any;


constructor(private httpClient: HttpClient) {
    this.httpClient.get('http://127.0.0.1:8000/api/employees')
};

}

HTML

<thead>

    <tr>

        <th scope="col">#</th>
        <th scope="col">Name</th>
        <th scope="col">Surname</th>
        <th scope="col">Email</th>
        <th scope="col">Salary</th>

    </tr>

</thead>

<tbody>

    <tr *ngFor="let emp of employees">
        <th scope="row">{{emp.id}}</th>
        <td>{{emp.name}}</td>
        <td>{{emp.surname}}</td>
        <td>{{emp.email}}</td>
        <td>{{emp.salary}}</td>
    </tr>

</tbody>


Solution 1:[1]

I see a couple of things, that cause the Data not to show up.

data.service.ts:

Your fetching the Data in the Constructor but you do ignore the return Value of your call. I suggest you do the call in a separate function that will be called if the data is needed.

constructor(private httpClient: HttpClient) {}

loadAllEmployees(): Observable<any> {
   return this.httpClient.get('http://127.0.0.1:8000/api/employees');
}

Employees Component:

It seems, that you do not call the getEmployeesData function. Therefore your employees never get any Data.


employees: any

constructor(private dataservice: DataService) { }

ngOnInit() {
   this.getEmployeesData();
}
getEmployeesData() {
    this.dataservice.loadAllEmployees().subscribe((res: any) => {
        this.employees = res;
    });
}

With this setup, your data should load and be displayed. Besides that, I would suggest you define the Type of the Employee and do not work with any. It does make it easier to read and understand your code. You are also less likely to get any Errors regarding types.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Motscha