如何将 json 数据传递给 Angular 中的 Class 变量?

How to pass json data to Class variable in Angular?

我有一个class个项目

export class Projects {
project_id: number;
project_name: string;
category_id: number;
project_type: string;
start_date: Date;
completion_date: Date;
working_status: string;
project_info: string;
area: string;
address: string;
city: string;}

它的服务class是

@Injectable()
export class ProjectsService {

  constructor(private http: HttpClient) {}

  //http://localhost:9090/projectInfo
private apiUrl = 'http://localhost:9090/projectInfo';

public findAll() {
  return this.http.get(this.apiUrl);
 }

 getProducts(): Observable<ProjectsModule[]> {
  return this.http.get<ProjectsModule[]>(this.apiUrl);
}

组件是

import { Component, OnInit } from '@angular/core';
import { ProjectsService } from '../projects.service';
import{Projects} from '../projects';
import { plainToClass, Transform, Expose, Type, Exclude } from 'class-transformer';
@Component({
  selector: 'app-project-list',
  templateUrl: './project-list.component.html',
  styleUrls: ['./project-list.component.css'],
  providers: [ProjectsService]
})
export class ProjectListComponent implements OnInit {

private projects:Projects[]=[];
stringObject: any;
  constructor(
   private projectsService: ProjectsService) { }
   vandana='rahul';
   
  ngOnInit() {
   this.getAllProjects();
   }


 getAllProjects() {
   this.projectsService.getProducts().subscribe((data: Projects[])=> {
      this.stringObject =JSON.stringify(data)
      let newTodo = Object.assign(new Projects(), data); 
      this.projects=  <Projects[]>this.stringObject;
      console.log("data  -"+ this.projects)
      console.log("Array  -"+ this.stringObject)
      console.log("data  -"+ this.projects[1].project_info)
      },
      
   err => {
   console.log(err);
   } 
   
  );
 
   }

当我尝试阅读 newTodo.project_id(或 class 项目的任何 属性)时,它是未定义的 但是 newtodo 正在返回 jsondata

输出是

请帮我获取值 newtodo.project_id、newtodo.project_name 等等

您正在将 JSON 字符串分配给 this.projects

JSON 字符串是 [{"projectId": 1, ... }]

所以:

  • this.projects[1] 的计算结果为 {(即字符串中的第二个字符)
  • "{".project_id 的计算结果为 undefined

您应该将数据本身分配给 this.projects:

this.projects = data;

然后记住 JavaScript 中的数组是从零开始的。由于数组中只有一个对象,因此必须按如下方式打印 projectId

console.log(this.projects[0].projectId);

此外,您的 Projects class 的属性与您的 JSON 完全不匹配。此外,Projects 可能应该命名为 Project,并且应该是一个接口而不是 class。