如果我问了太愚蠢的问题,我提前道歉,但我真的是angular的新手,我不知道如何处理来自服务器的JSON对象,并将该对象转换为自定义数据类型,以便我可以使用该数据使用ngFor在html上渲染.

我试过很多方法,但似乎都不起作用.任何帮助将非常感谢.

另外,请原谅我非常简单的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只能用在observable和iterator上.下面是如何从服务器中提取对象的附加图像,当我点击getAllEmployees按钮时,它只是呈现对象本身.如果我不直接打电话给{{ employees }},我无法打印数据.

enter image description here

Error Page: Error Image

推荐答案

这是因为您需要将employees变量初始化为空数组,因为它总是在第一次加载时运行,只有在单击按钮之后,您才能获得数组集.

employees: any = [];

这是一个模拟的堆叠闪电战,效果很好.需要注意的几点是:

  1. If the 服务 is provided in root, then you need to inject the dependencies

就像这样.

private http = Inject(HttpClient);

服务

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'});
  }
}

双手

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.服务';

@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);

stackblitz

Typescript相关问答推荐

如果我有对象的Typescript类型,如何使用其值的类型?

如何防止TypeScript允许重新分配NTFS?

React router 6.22.3不只是在生产模式下显示,为什么?

接口的额外属性作为同一接口的方法的参数类型'

如何在TypeScrip面向对象程序设计中用方法/属性有条件地扩展类

在TypeScrip中分配回调时,参数的分配方向与回调本身相反.为什么会这样呢?

泛型类型联合将参数转换为Never

带switch 的函数的返回类型的类型缩小

正交摄影机正在将渲染的场景切成两半

如何获取受类型脚本泛型约束的有效输入参数

如何连接属性名称和值?

从类型脚本中元组的尾部获取第n个类型

如何从上传文件中删除预览文件图标?

错误TS7030:并非所有代码路径都返回值.";由tsfig.json中的";Strong";:False引起

在REACT查询中获取未定义的isLoading态

仅当类型为联合类型时映射属性类型

如何使对象同时具有隐式和显式类型

如何键入';v型';

可以';t使用t正确地索引对象;联合;索引类型

TypeScript是否不知道其他函数内部的类型判断?