user6701863 user6701863 - 3 months ago 9
TypeScript Question

How to easily consume an API response, but add some additional flags to the response?

I am using an API that returns some data to me about photos, but I want to add a flag to the response I get called

favorite: boolean
so I can easily manage whether or not the photo is a favorite or not.

The vanilla response from the API looks something like this (but much simpler):

{
"photos": [
{ "id": 1001, "url": "site.com/img/1001" },
{ "id": 1002, "url": "site.com/img/1002" }
]
}


I am wondering if there is a way to add the
favorite
flag so that the object I work with looks like this:

{
"photos": [
{ "id": 1001, "url": "site.com/img/1001", "favorite": false },
{ "id": 1002, "url": "site.com/img/1002", "favorite": false }
]
}


Here is my code where I get the response from the API:

getRecentPhotos(): Observable<any> {
let photos = this.http
.get(this.getRecentPhotosUrl)
.map((res: Response) => {
return res.json();
})
.catch(this.handleError);
return photos;
}


Is it possible to add the
favorite
flag to the response I get back from that function?

Thanks

Answer

You have most of the code, you just need to add favorite flag in mapper,

.map((res: Response) => {
    let _result = res.json();
    _result = _result.map(_x => {
          _x.favorite = false;
          return _x;
    })
    return _result ;
  })

Hope this helps!!