Angular 为什么在subscribe未定义后从服务获取数据?
我定义了一个接口Angular 为什么在subscribe未定义后从服务获取数据?,angular,typescript,web-services,Angular,Typescript,Web Services,我定义了一个接口 export interface IEmployee { maNV?:number, hoTen?:string, gioiTinh?:string, ngaySinh?:Date, diaChi?:string, cmnd?:string, sdt?:string, luong?:number, ngayBatDauLam?:Date, maNguoiQuanLy?:number, isD
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
}
我创建了一个文件employee.json
包含一些员工的信息:
[
{"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}
]
然后我创建一个服务,从employee.json
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);
}
}
我发现
这个。数据是未定义的。我不知道为什么我定义它是数组。并帮助我将其转换为数组类型,这是因为您在httpClient获取数据之前记录了数据,请记住httpClient.get是一种异步方法,如果需要,可以将console.log移动到订阅中,并且它应该可以正常工作:
ngOnInit():void
{
this.service.getEmployees().subscribe(data=>{
this.data=data;
console.log(this.data);
}) ;
}
这是因为您是在httpClient获取数据之前记录数据的,请记住httpClient.get是一个异步方法,如果您希望将console.log移动到订阅中,它应该可以正常工作:
ngOnInit():void
{
this.service.getEmployees().subscribe(data=>{
this.data=data;
console.log(this.data);
}) ;
}