Parsing JSON to Object in Angular 2

Discussão em 'Angular' iniciado por kenadet, Novembro 10, 2024.

  1. kenadet

    kenadet Guest

    I have a file location.json, containing JSON string of the form:

    {
    "locations": [
    {
    "id": 1,
    "places": [
    {
    "id": 1,
    "city": "A",
    "state": "AB"
    }
    ]
    }
    }


    I created classes of the form:

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

    export class Place {
    constructor(
    public id: number,
    public city: string,
    public state: string
    }


    How do I parse the JSON string to object? I did something like this:

    ...
    export class DashboardComponent {

    locations: Locations[];

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

    getLocations(){
    this.locationService.get('assets/location.json')
    .subscribe(res => this.location = res);
    }

    Continue reading...

Compartilhe esta Página