I have developed a straightforward application for calling backend services using HttpClientModule. However, I am encountering an issue where the data is not displaying in the log. Below are the steps that I followed, and I am working with Angular-9.
Could you please review the code?
Thank you in advance.
- app.module file
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule} from '@angular/common/http';
import {RestAPIServices} from './services/rest-api.service';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [RestAPIServices],
bootstrap: [AppComponent]
})
export class AppModule { }
- model.ts
export class Employee{
id:number;
name:string;
gender:string;
email? :string; // ? means optional property
mobile:string;
department:string;
isActive:boolean;
photo? :string;
}
- service.ts
import {Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import {HttpClient} from '@angular/common/http';
import { Employee } from '../models/employee.model';
@Injectable()
export class RestAPIServices{
constructor(private httpClient:HttpClient){}
getEmployee():Observable<Employee[]>{
//this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees").subscribe(res=> console.log(res));
return this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees");
}
}
- app.component.ts
import { Component } from '@angular/core';
import {RestAPIServices} from './services/rest-api.service';
import {Employee} from './models/employee.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
listEmployee : Employee[];
title = 'simple-rest-app';
constructor(private _employeeService:RestAPIServices){}
ngOnInit(){
this._employeeService.getEmployee().subscribe(
data=>{
console.log(data)
this.listEmployee = data;
}
)
console.log(this.listEmployee);
}
}
The service has been tested using Postman and is functioning correctly.
{"response":[{"id":"1","name":"Anand","gender":"Male","email":"example@example.com","mobile":"111111111","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"2","name":"Kiran","gender":"Female","email":"example2@example.com","mobile":"2222222222","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"3","name":"Ravi","gender":"Male","email":"example3@example.com","mobile":"3333333333","department":"2","isActive":"1","photo":"assets\/images\/emp2.jpg"},{"id":"4","name":"Kumar","gender":"Male","email":"example4@example.com","mobile":"4444444444","department":"3","isActive":"1","photo":"assets\/images\/emp4.jpg"}]}