1

Suppose I have the class

export class DummyClass {
   name: string;
   value: number = 10;
}

So a class that holds only name and value with a default value of 10.

If I now want to get data from the server and I initiate my call.

this.httpClient.post<DummyClass>(...)

And the json response is

{
   "name": "john doe"
}

Then my class also looks like this. This implies I have complete lost my property value with its default value as wel. And this was the whole point of my default value -> such that the server does not need to send default values.

How can I correctly map the json response to a model and not lose default values.

1 Answer 1

1

First of all, when you fetch data from an API, you don't get a class instance. You get a plain object.

This means that your API response follows the class interface, but does not instanciate it.

There might be some libraries around to do that, haven't checked.

To resolve your issue, you can use a pipe in your API call :

this.http.post<DummyClass>(...).pipe(
  map(res => {
    const instance = new DummyClass();
    Object.assign(instance, res);
    return instance;
  })
);

There a LOTS of ways to do it, with each having their pros and cons, but this one is the most broad and simple one I think.

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

2 Comments

I have been thinking about that solution as well (to pipe-map them) but the problem with this is with nesting. if the class with default value isn't the root object but some child object of the root object than this Object.assign solution wont work either.
That's why I said there is multiple solutions to it. I found a library that could do it for you : github.com/typestack/class-transformer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.