How to Map RESTful API Data Using Decorator Pattern in Angular
To build a solid RESTful API, there are well-established best practices and design patterns we can use. In this article, I will discuss using the Decorator pattern to consume RESTful API in Angular.
HttpClient Service
To consume a REST API in Angular, we can use HttpClient
. HttpClient
service handles the JSON data parsing under the cover and returns an Rxjs observable. It also supports generic typing functionality. For example, in the code snippet below, getAllTodos
will return an observable with an array of objects that match the type TodoModel.
constructor(private http: HttpClient) {}getAllTodos(): Observable<TodoModel[]> {
return this.http.get<TodoModel[]>(this.url);
}
It is straightforward to make use of HttpClient
to call the REST API and get the data to bind to the view.
The Problem
All seems good so far, but problems start to arise when the backend changes. Let’s say we have the TodoModel
as below.
export class TodoModel{
public name: string;
public id: number,
public completed: boolean,
}