0

In my Angular2 app I have a Injectable WebcamsService. This service should get all webcams or add a new webcam.

....

@Injectable()
export class WebcamsService {

  constructor (private http: Http) {}

   getWebcams(id: number) {
     ...
   }


  addWebcam(...) {
    ...
  }

}

The response of the API ( GET /api/v1/webcams ):

{
  "data": [
    {
      "id": 1,
      "url": "http://www.xyz.de",
      "name": "WebcamName",
      "location": {
         "country": "XY",
         "city": "Z"
      }
    },
    {
      "id": 1,
      "url": "http://www.xyz.de",
      "name": "WebcamName",
      "location": {
         "country": "XY",
         "city": "Z"
      }
    }
  ]
}

The response of the API (POST /api/v1/webcams):

{
  "data": {
    "spot_id": "1",
    "name": "X",
    "url": "Y",
    "location": {
       "country": "XY",
       "city": "Z"
    }
  }
}

Now of course I want to map these responses to objects. The classes are looking like this:

Webcam-model

export class Webcam {
  id: number;
  url: string;
  name: string;
  location: Location;
}

Location-model

export class Location {
  country: string;
  city: string;
}

Now I have to map the response to my objects. I think there are several options:

  • A mapping-function in the service
  • Mapping in the constructor (pass json to the constructor of the model)

Are there any more options? Which option should I use?

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
rakete
  • 2,953
  • 11
  • 54
  • 108

0 Answers0