I have created an interface as follows:
export interface IEmployee
{
maNV?:number,
hoTen?:string,
gioiTinh?:string,
ngaySinh?:Date,
diaChi?:string,
cmnd?:string,
sdt?:string,
luong?:number,
ngayBatDauLam?:Date,
maNguoiQuanLy?:number,
isDelete?:boolean
}
In a file named employee.json
, I have stored information about some employees:
[
{"maNV":1,"hoTen":"nguyen quang du","gioiTinh":"nam","ngaySinh":"03/02/1999","diaChi":"Hà Tây","cmnd":"1131131231231232","sdt":3123123141,"luong":300,"ngayBatDauLam":"03/01/2020","maNguoiQuanLy":1,"isDelete":false},
{"maNV":2,"hoTen":"nguyen thi duyen","gioiTinh":"nu","ngaySinh":"03/02/1999","diaChi":"Hà Tây","cmnd":"1131131231231232","sdt":3123123141,"luong":300,"ngayBatDauLam":"03/01/2020","maNguoiQuanLy":1,"isDelete":false},
{"maNV":3,"hoTen":"khuat quang chien","gioiTinh":"nam","ngaySinh":"03/02/1999","diaChi":"Hà Tây","cmnd":"1131131231231232","sdt":3123123141,"luong":300,"ngayBatDauLam":"03/01/2020","maNguoiQuanLy":1,"isDelete":false}
]
To fetch the data of employees from employee.json
, I have created a service:
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http'
import {IEmployee} from './employee/employee'
import {Observable} from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
private _url:string="../assets/data/employees.json";
constructor(private http:HttpClient) {}
getEmployees():Observable<IEmployee[]>
{
return this.http.get<IEmployee[]>(this._url);
}
}
Subsequently, I created a component to retrieve the employee data using the method getEmployee()
. The main code snippet looks like this:
public data:Array<IEmployee>;
constructor(private service:EmployeeService){}
ngOnInit():void
{
this.service.getEmployees().subscribe(data=>this.data=data) ;
console.log(this.data);
}
However, upon inspection, I discovered that this.data
is being displayed as undefined
. I am unsure why this is happening, especially since I have defined it as type Array<IEmployee>
. Can someone please assist me in converting it correctly?