When calling a RESTful service that returns data with many fields, I needed to create an interface similar to a DTO to only carry the necessary data. To achieve this, I utilized pipe & map from rxjs, but I am unsure if this is considered best practice:
The usual returned data:
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aaf9c3c4c9cfd8cfeacbdad8c3c684c8c3d0">[email protected]</a>",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{...}
]
The data I need:
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9ead0d7dadccbdcf9d8c9cbd0d597dbd0c3">[email protected]</a>"
},
{...}
]
User Interface:
export interface User {
id?:number,
name?:string,
email?:string,
username?:string
}
User Service:
export class UsersService {
constructor(private http: HttpClient) {}
getAllUsers(): Observable<User[]> {
return this.http.get<User[]>("https://jsonplaceholder.typicode.com/users")
.pipe(
map((data: User[]) =>
data.map((item: User) => {
return {
id: item.id,
name: item.name,
email: item.email,
username: item.username,
};
})
)
);
}
}