如果我问了太愚蠢的问题,我提前道歉,但我对 Angular 真的很陌生,我不明白如何处理来自服务器的 JSON 对象并将该对象转换为自定义数据类型,以便我可以使用该数据来渲染在 html 上使用 ngFor。
我尝试了多种方法,但似乎没有任何效果。任何帮助将非常感激。
附注请原谅我的 html 页面非常简单,应用程序是从头开始的,我正在研究功能和后端服务器连接,然后再进行设计。
下面是附加的代码和屏幕截图。
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
){}
}
我想将来自服务器的 JSON 数据转换为 AddEmployee 类型,然后在 html 中运行 ngFor 循环,这样我就可以将所有内容放入表格格式。
但是 Angular 一直抱怨我得到的数据是对象格式,而 ngFor 只能用于可观察值和迭代器。下面是如何从服务器提取对象的图像,当我单击 getAllEmployees 按钮时,它只渲染对象本身。如果我不直接调用 {{Employees}},我将无法打印数据。
这是因为您需要将
employees
变量初始化为一个空数组,因为它总是在第一次加载时运行,只有在单击按钮后,您才能获取数组集。
employees: any = [];