【问题标题】:Is there any way to cast Json Object in angular有没有办法以角度投射 Json 对象
【发布时间】: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 =&gt; { this.emp=data; console.log(this.emp}); } }

标签: json angular


【解决方案1】:
 Just define type when passing variable in subscribe 
   getEmployee() : void{
       this.employeeService.getEmployee().subscribe((data:Employee)=>{
          this.emp=data;
}  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-07
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2018-08-10
    相关资源
    最近更新 更多