有什么方法可以将Json Object转换为angular

时间:2019-06-27 06:49:54

标签: json angular

能够以JSON对象的形式接收来自服务器的响应。试图将JSON对象转换为emp(类型Employee),但没有发生。我的代码有什么问题?还有另一种方法可以解决这个问题吗?

app.component.ts

export class AppComponent implements OnInit{
  title = 'httpClientProject';

  posts : JsonGet[];
  emp : Employee;

  constructor(private appService : AppService,private employeeService : EmployeeService){}

ngOnInit(){
  this.getData();
  this.getEmployee();
console.log(this.emp)  }

getData() : void{
  this.appService.getData().subscribe(posts=>(this.posts = posts));   }

getEmployee() : void{
   this.employeeService.getEmployee().subscribe(data=>this.emp={...data});   }   }

employee.service.ts

export class EmployeeService {

    private baseUrl = 'http://localhost:8080/SpringRestWebService/getSingleEmployye';

    constructor(private http: HttpClient) { }

     getEmployee(): Observable<Employee> {
             return this.http.get<Employee>(this.baseUrl);  }   }

Employee.ts

export class Employee {

    public id: number;
    public name: string;
    public city: string;

    constructor(id:number, name:string, status:string) {
      this.id = id;
      this.name = name;
      this.city = status;    }     }


Json Response From Server

{
    "id": 1,
    "name": "asdasd",
    "city": "Hasdasdayd"
}

1 个答案:

答案 0 :(得分:-1)

 Just define type when passing variable in subscribe 
   getEmployee() : void{
       this.employeeService.getEmployee().subscribe((data:Employee)=>{
          this.emp=data;
}  
}