无法将从服务器接收的单个JSON对象转换为所需类型,因此可以分析数据

2ul0zpep  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(75)

如果我问了太愚蠢的问题,我提前道歉,但我真的是angular的新手,我不知道如何处理来自服务器的JSON对象,并将该对象转换为自定义数据类型,以便我可以使用该数据使用ngFor在html上渲染。
我已经尝试了多种方法,但似乎都不起作用。任何帮助都将非常感谢。
P.S.请原谅我非常简单的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>

x

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一直抱怨我得到的数据是Object Format,ngFor只能在observables和iterators上使用。下面是如何从服务器中提取对象的图像,当我点击getAllEmployees按钮时,它只是呈现对象本身。如果我不直接调用{{ employees }},我就无法打印数据。
x1c 0d1x的数据



当我在stackBlitz中尝试相同的代码时,我能够很好地看到它。但是我的本地浏览器一直给我这个问题。我认为这与我试图在html中运行的ngfor循环有关,但我不知道任何其他方法来解决这个问题,因为我是angular的新手。

mu0hgdu0

mu0hgdu01#

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

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

字符串
最初这些值是未定义的,所以当你试图访问一个未定义值的属性时,你会得到这个错误,因此如果我们将值定义为{},直到正确的值被设置,你不会得到这个错误!

相关问题