Typescript, Angular 2 - Parse Json for an object in http

I have a file location.jsoncontaining the json line of the form:

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

I created form classes:

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 a json string for an 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);
  }
+4
source share
2 answers

Depending on the result for the subscriber, this may be:

.map(res => this.location = res.json().locations);

Or:

.subscribe(res => this.location = JSON.parse(res).locations);

But keep in mind that this will not stimulate instances for your classes, it will only assign values ​​as a regular js object, which corresponds to the following:

interface Location {
    id: number;
    places: Place[];
}

interface Place {
    id: number;
    city: string;
    state: string;
}

If you need class instances, you need to do something like:

JSON.parse(res)
    .locations.map(location => new Location(location.id, 
        location.places.map(place => new Place(place.id, place.city, place.state)))
+6
source

res => res.json() - , json , .

, , , .

  return this.http.get(url,options).map((response) => this.parseResponse(response))
        .catch((err) => this.handleError(err));

  private handleError(error: any) {
    let body = error.json();

    return Observable.throw(body);
  }

  private parseResponse(response: Response) {
    return response.json();
  }
0

Source: https://habr.com/ru/post/1677276/


All Articles