reyesoft / ngx-jsonapi

JSON API client library for Angular 5+ 👌 :: Production Ready 🚀
https://ngx-jsonapi.reyesoft.com/
MIT License
101 stars 52 forks source link

Creating new resource wipes all attributes #177

Closed PiotrBrzezianski closed 4 years ago

PiotrBrzezianski commented 5 years ago

I wanted to have some defaults in the class that inherits from Resource when I've noticed that calling service.new() wipes the attributes object to an empty one.

public reset(): void {
    this.id = '';
    this.attributes = {};
    this.is_new = true;

    for (const key in this.relationships) {
        this.relationships[key] =
            this.relationships[key] instanceof DocumentCollection ? new DocumentCollection() : new DocumentResource();
        }
    }

Any reason this has to be like that? If this is intentional can it be made optional?

maxi7587 commented 5 years ago

You can instantiate the resource class using new YourResourceClass(). This should use your default values.

PiotrBrzezianski commented 5 years ago

Sure I can reproduce what the Service.new() method would do but that doesn't feel right. It links up the service to the resource and sets the type up. It seems to me that it is perfectly acceptable that reset method is clearing things up but I'm not sure why new() should be calling into reset()...

pablorsk commented 4 years ago

You need to use Service.new() for obtain a clean reset and clean Resource. On v2.1.x, version we work on this funciton, now work better! And is fully tested :)

Please, if you detect an error, open a PR o just comment here with an example (actual and spected result)

pandabamboo90 commented 3 years ago

I had the same issue, however as @maxi7587 suggested, I can init new user with default attributes

this.user = this.userApi.new();
this.user.attributes = new User().attributes;