Paldom / angular2-rest

Angular2 HTTP client to consume RESTful services. Built with TypeScript.
MIT License
248 stars 72 forks source link

Transforming the response #13

Open marekpw opened 8 years ago

marekpw commented 8 years ago

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.

ardf69 commented 8 years ago

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

marekpw commented 8 years ago

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.

ardf69 commented 8 years ago

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