Is there a way to extract raw data from a JsonApiModel?
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.
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.
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 :)
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;
}
}
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;
}
}