1

I have an object that I send using HttpClient who may have some null properties. I wonder if there are any build-in solution(s) in Angular that ensure that null properties are not serialized.

Lets take this model for instance:

export class Dummy {
  public constructor(
    public readonly foo: string,
    public readonly bar: string
  ) { }
}

And this service:

import { HttpClient } from '@angular/common/http';

export class DummyService {
  public constructor(private readonly httpClient: HttpClient) { }

  public dummyMethod(dummyObject: Dummy): Observable<any> {
    return this.httpClient.Post('https://api.dummy/v1/dummies', dummyObject)
  }
}

If dummyObject === new Dummy("FooValue", null) then I expect this JSON to be serialized: { "foo": "FooValue" }

1
  • 1
    could you use undefined instead of null? JSON.stringify, which is user under the hood by the HttpClient, will ignore properties that are undefined Commented Jun 4, 2019 at 15:25

1 Answer 1

3

In JSON, values must be one of the following data types:

a string
a number
an object (JSON object)
an array
a boolean
null

So it can't ignore null. But we can't see undefined here, so you can use it instead of null and serialised object will omit it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.