【发布时间】:2019-06-29 12:38:29
【问题描述】:
能够以 JSON 对象的形式接收来自服务器的响应。尝试将 JSON 对象转换为 emp(员工类型),但没有发生。我的代码有什么问题??有没有其他方法可以解决这个问题??
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); } }
员工.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"
}
【问题讨论】:
-
this.emp={...data});这里不需要解构。 -
即使 this.emp=data 也不起作用
-
究竟是什么不起作用?
-
当我尝试在控制台中打印 emp 时,它说 emp 未定义
-
你在哪里打印?
.subscribe(data => { this.emp=data; console.log(this.emp}); } }