Ignore JSON properties from Angular HTTP requests using jsonIgnore

Cosmin Crişan
2 min readJun 10, 2021
Photo by Tim Mossholder on Unsplash

Most of the time, in our web applications, we read data from the server in order to display it to the user giving him the ability to manipulate that data.

In our Angular applications, the provided data is stored most of the time in objects. We then use those objects in our HTML pages. In addition to the fields read from the server, there may be fields that are used only for the design part and should not be read from the server or sent to it. In this article, I will show you a simple way to do this using npm package json-ignore.

First we need to install npm package using:

npm install json-ignore --save

After the package is installed, we need to make sure that tsconfig.json file contains the following 2 required fields in compilerOptions object:

{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}

Now everything is set and we can use the json-ignore package with no problem.

Let’s consider a class named User with the following fields:

1. firstName: string 
2. lastName: string
3. age: number
4. showInList: boolean // not read from the server
// not sent to the server

showInList field is not read from the server and is modified and used only by the web application to manipulate HTML templates. After the user data is updated and sent back to the server, showInList field must not be sent.

We will use @jsonIgnore() attribute to mark the fields that we want to ignore as follows:

Now it’s time to create / update our data and send it to the server.

For this, we will a create a new service that will communicate with our server:

In our service, we have 2 methods: one that sends the entire user data to the server and one that will remove the ignored fields.

All we have to do to remove the fields marked with @jsonIgnore() is to serialize the object passing jsonIngoreReplacer function as the second parameter.

const data = JSON.stringify(user, jsonIgnoreReplacer);

The result is:

saveUserWithJsonIgnore function

instead of:

saveUser function

This was an overview on how you can ignore fields from serialization when sending data to the server. You can find the full source code here.

--

--

Cosmin Crişan

Full Stack Developer. Passionate about technology and software development.