小编Ken*_*det的帖子

Typescript,Angular 2 - 将Json解析为http中的对象

我有一个文件location.json,包含以下形式的json字符串:

{
  "locations": [
    {
      "id": 1,
      "places": [
        {
          "id": 1,
          "city": "A",
          "state": "AB"
        }
      ]
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了表单的类:

export class Location{
       constructor(public id: number,
        public places: Place[],
     }

export class Place {
        constructor(
        public id: number, 
        public city: string,
        public state: string
} 
Run Code Online (Sandbox Code Playgroud)

如何将json字符串解析为object?我做了这样的事情:

...
export class DashboardComponent {

  locations: Locations[];

  constructor(private locationService:LocationService) {
    this.getLocations() 
  }

  getLocations(){
      this.locationService.get('assets/location.json')
      .subscribe(res => this.location = res);
  }
Run Code Online (Sandbox Code Playgroud)

parsing json typescript angular2-services angular

4
推荐指数
2
解决办法
7712
查看次数

标签 统计

angular ×1

angular2-services ×1

json ×1

parsing ×1

typescript ×1