无法将从服务器接收到的单个 json 对象转换为所需类型,以便剖析数据

问题描述 投票:0回答:1

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

我尝试了多种方法,但似乎没有任何效果。任何帮助将非常感激。

附注请原谅我的 html 页面非常简单,应用程序是从头开始的,我正在研究功能和后端服务器连接,然后再进行设计。

下面是附加的代码和屏幕截图。

Employee.Component.html
<div>
    <br>
    <h2>Employee Data</h2>
    <table border="1">
    <thead>
      <th *ngFor="let column of columns">
        {{column}}
      </th>
    </thead>
    <tbody>
      <tr *ngFor="let row of empById; index as i">
        <td *ngFor="let column of columns; index as j">
          {{row[column]}}
        </td>
      </tr>
    </tbody>
    </table>
  </div>
employee.component.ts file:
 columns = [
    'employeeId',
    'firstName',
    'lastName',
    'address',
    'project',
    'ssn',
    'joinDate',
    'status',
  ];
 
  empById: any;
  empId: any;
 constructor(private testService: TestService) {}
  ngOnInit() {}
public getEmployeesById() {
    console.log('get Details for id: ' + this.empId);
    this.testService.getEmployeeById(this.empId).subscribe({
      next: (data) => {
        this.empById = data;
        console.log('Response: ' + this.empById);
      },
      error: (error) => {
        console.error('Error fetching employees: ', error);
      },
    });
  }
EmployeeService file:
@Injectable({
  providedIn: 'root'
})
export class EmployeeServiceService {

  constructor(private http:HttpClient) { }

  getEmployeeById(empId:number): Observable<GetEmployee[]>{
    console.log("Inside get Employees By Method.");
    return this.http.get<GetEmployee[]>("https://localhost:9090/employee/getEmployeeById/"+empId,{responseType:'text' as 'json'});
  }
  }
GetEmployee class type:

export class GetEmployee{
    employeeId:any
firstName: any;
    lastName: any;
    address:any;
    project:any
    ssn:any;
    joinDate:any;
    status:any

        constructor(
employeeId:number
            firstName: string,
            lastName: string,
            address:string,
            project:string,
            ssn:number,
            joinDate:Date,
            status:number
        ){}
    }

我想将来自服务器的 JSON 数据转换为 GetEmployee 类型,然后在 html 中运行 ngFor 循环,以便我可以将所有内容放入表格格式。

但是 Angular 一直抱怨我得到的数据是对象格式,而 ngFor 只能用于可观察值和迭代器。下面是如何从服务器提取对象的图像,当我单击 getAllEmployees 按钮时,它只渲染对象本身。如果我不直接调用 {{Employees}},我将无法打印数据。

当我在 stackBlitz 中尝试相同的代码时,我可以很好地看到它。但我的本地浏览器一直给我这个问题。我认为这与我尝试在 html 中运行的 ngfor 循环有关,但我不知道有任何其他方法来解决这个问题,因为我对 Angular 非常陌生。

arrays json angular variable-assignment angular16
1个回答
0
投票

employee.component.ts
中请将初始化设置为
{}

empById: any = {};
empId: any = {};

最初这些值是未定义的,因此当您尝试访问未定义值的属性时,您会收到此错误,因此如果我们将值定义为

{}
直到设置正确的值,您将不会收到此错误!

© www.soinside.com 2019 - 2024. All rights reserved.