angular2-jsonapi icon indicating copy to clipboard operation
angular2-jsonapi copied to clipboard

Is there a way to extract raw data from a JsonApiModel?

Open Liranius opened this issue 7 years ago • 4 comments

For some reason I need to clone a data model. If I can extract raw data from JsonApiModel, I can call createRecord to create a new model instance with same value from old model.

Liranius avatar Mar 26 '18 03:03 Liranius

By the way, createRecord is not deep cloning object passed in, so one may need to deep clone the object passed in to avoid passing by reference.

Liranius avatar Mar 26 '18 03:03 Liranius

Hhmm, that would also help a lot in Angular reactive forms. Angular has patchValue() which takes simple object and fills the form for you recursively based on attribute names. I don't see a method to get original attribute names from JsonApiModel. They are prefixed with _ by setter therefore I can either update form names or create new method to get original attributes. I prefer to update my form controls :)

wojo1206 avatar Mar 26 '19 18:03 wojo1206

I ended up extending JsonApiModel and providing a function to return original data like in this sample.

class MyJsonApiModel extends JsonApiModel {
  getFormPatch(datastore) {
    const props = {
      id: this.id,
      type: this.type
    };
    const names = datastore.getModelPropertyNames(this);
    for (const prop in names) {
      if (names.hasOwnProperty(prop)) {
        props[prop] = this[prop];
      }
    }
    return props;
  }
}

wojo1206 avatar Apr 25 '19 15:04 wojo1206

import { JsonApiModel } from 'angular2-jsonapi';
import * as _ from 'lodash';

export class BaseModel extends JsonApiModel {

  getAttributes(): { [key: string]: any } {
    let attributes: any = Reflect.getMetadata('Attribute', this);
    attributes = _.keys(attributes);
    return _.pick(this, attributes);
  }

  fillAttributes(newValue: any): this {
    let attributes: any = Reflect.getMetadata('Attribute', this);
    attributes = _.keys(attributes);
    _.forEach(attributes, (attribute: string) => {
      this[attribute] = newValue[attribute] || this[attribute];
    });
    return this;
  }
}

phuchnh avatar Oct 14 '19 05:10 phuchnh