Issue
I apologize in advance if i am asking too stupid questions but i am really new to angular and i do not understand how to handle a JSON object coming from the server and convert that object into a custom datatype so i can use that data to render on html using ngFor.
I have tried multiple things but nothing seems to work. Any help will be very much appreciated.
P.S. please excuse me for the extremely simple html page, application is coming up from scratch and i am working on functionalities and backend server connections before working on the designs.
Below is the Code and screenshots attached.
Employee.Component.html
<p>Inside Employee Component.</p>
<button type="submit" class="btn btn-login float-center" (click)="getAllEmployees1()">getAllEmployees</button>
<div>
<h2>Employee List</h2>
{{ employees }}
</div>
employee.component.ts file
employees: any;
constructor(private service: EmployeeServiceService){
}
ngOnInit(){
}
public getAllEmployees1(){
this.service.getAllEmployees().subscribe((data)=>{
this.employees = data;
console.log("Response: "+ this.employees);
},
(error) =>{
console.error('Error fetching employees: ', error);
}
);
}
EmployeeService file:
@Injectable({
providedIn: 'root'
})
export class EmployeeServiceService {
constructor(private http:HttpClient) { }
getAllEmployees(){
console.log("Inside get ALL Employees Method.");
return this.http.get("https://localhost:9090/employee/getAllEmployees",{responseType:'text' as 'json'});
}
Employee class type:
export class AddEmployee{
firstName: any;
lastName: any;
address:any;
project:any
ssn:any;
joinDate:any;
status:any
constructor(
firstName: string,
lastName: string,
address:string,
project:string,
ssn:number,
joinDate:Date,
status:number
){}
}
I wanted to convert the JSON data coming from the server to AddEmployee type and then run a ngFor loop in the html so i can put everything in the tabular format.
But angular keeps on complaining that the data i am getting is in Object Format and ngFor can only be used on observables and iterators. Below is the image attached of how the object gets pulled from server and when i click on getAllEmployees button, it just renders the object itself. I am not able to print the data if i dont call {{ employees }} directly.
Solution
Its because you need to initialize the employees
variable to an empty array, since it always runs on first load, only after the button is clicked, you are getting the array set.
employees: any = [];
Here is a mock stackblitz which works fine. Few points to note are:
- If the service is provided in root, then you need to inject the dependencies
like so.
private http = Inject(HttpClient);
service
import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { of } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class TestService {
private http = Inject(HttpClient);
constructor() {}
getAllEmployees() {
console.log('Inside get ALL Employees Method.');
return of([
{
firstName: 'test',
lastName: 'test',
address: 'test',
project: 'test',
ssn: 'test',
joinDate: 'test',
status: 'test',
},
{
firstName: 'test',
lastName: 'test',
address: 'test',
project: 'test',
ssn: 'test',
joinDate: 'test',
status: 'test',
},
{
firstName: 'test',
lastName: 'test',
address: 'test',
project: 'test',
ssn: 'test',
joinDate: 'test',
status: 'test',
},
{
firstName: 'test',
lastName: 'test',
address: 'test',
project: 'test',
ssn: 'test',
joinDate: 'test',
status: 'test',
},
]); //this.http.get("https://localhost:9090/employee/getAllEmployees",{responseType:'text' as 'json'});
}
}
main.ts
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { AddEmployee } from './add-employee';
import { TestService } from './test.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [HttpClientModule, CommonModule],
template: `
<p>Inside Employee Component.</p>
<button type="submit" class="btn btn-login float-center" (click)="getAllEmployees1()">getAllEmployees</button>
<div>
<h2>Employee List</h2>
{{ employees | json}}
<table border="1">
<thead>
<th *ngFor="let column of columns">
{{column}}
</th>
</thead>
<tbody>
<tr *ngFor="let row of employees; index as i">
<td *ngFor="let column of columns; index as j">
{{row[column]}}
</td>
</tr>
</tbody>
</table>
</div>
`,
})
export class App {
columns = [
'firstName',
'lastName',
'address',
'project',
'ssn',
'joinDate',
'status',
];
employees: Array<AddEmployee> = [];
constructor(private testService: TestService) {}
ngOnInit() {}
public getAllEmployees1() {
this.testService.getAllEmployees().subscribe({
next: (data) => {
this.employees = data;
console.log('Response: ' + this.employees);
},
error: (error) => {
console.error('Error fetching employees: ', error);
},
});
}
}
bootstrapApplication(App);
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.