angular2-rest icon indicating copy to clipboard operation
angular2-rest copied to clipboard

Transforming the response

Open marekpw opened this issue 8 years ago • 3 comments

I'm new to observables and this service seems to use them heavily. I'd like to transform the response so that it creates a collection (on GET resource/) of entities implementing an interface describing them, or a single entity on GET resource/id.

The response from my API is something like this:

{
    data: [
        {
            id: 1,
            name: "some name"
        },
        {
            id: 2,
            name: "some name"
        },
    ],
    meta: {
        page: 1,
        totalPages: 14
    }
}

The method to receive this object is pretty basic:

@GET('/titles')
public getTitles(@Query('page') page: number): Observable<any>
{
    return null;
}

In my component which injects this Rest client, I use:

this.client.getTitles(page).subscribe(res => {
    console.log(res.json());
})

Now, I have two options:

  1. the ugly solution: Pass the res.json() results to another service in the observer callback which transforms the data array of the response to an array of entities. The downside is that I'd have to copy-paste this everywhere I want to get the data from the client.

  2. the nice solution: Somehow transform the response into entities in the client itself, then just pass the array of entities to the observer callback.

Any help is welcome.

marekpw avatar Mar 19 '16 21:03 marekpw

You can implement the method responseInterceptor or you can use @Produces(MediaType.JSON)

ardf69 avatar Apr 14 '16 20:04 ardf69

Thank you, I wasn't aware of the responseInterceptor method. It will be possible, although a bit messy, due to multiple data outputs based on if I fetch a single resource or a collection.

Could you please explain what does the @Produces decorator do? It's not documented anywhere.

marekpw avatar May 08 '16 16:05 marekpw

I found it in the code. At the moment it accepts only MediaType.JSON and, if it is specified, the observable passes to the next subscriber a json object instead of a Response object.

Ciao Angelo

ardf69 avatar May 09 '16 09:05 ardf69