How to Map RESTful API Data Using Decorator Pattern in Angular

A cleaner, loosely coupled, and maintainable solution

Sunny Sun

--

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 back end changes. Let’s say we have the TodoModel as below.

export class TodoModel{
public name: string;
public id: number,
public completed: boolean,
}

Two changes are required.

  1. We want to display a text description of “completed” when the value is true and display “pending” if the value is false.
  2. The field name is changed from “name” to “title”.

The quick way to meet the requirements is to change the model.

export class TodoModel{
public title: string;
public id: number,
public completed: string,
}

Then change the todo service to map the completed field.

getAllTodos(): Observable<TodoModel[]> {
return this.http.get(this.url).pipe(
map((data: any[]) => data.map((item: any) => {
const model = new TodoModel();
Object.assign(model, item);
if(item.completed){
model.completed = 'completed';
}else{
model.completed = 'pending';
}
return model;
}))
);
}

--

--

Sunny Sun

I am full stack developer. Love coding, always leaning, writing and sharing. Visit my personal blog https://sunnyy02.github.io