Skip to content

Instantly share code, notes, and snippets.

@mppfiles
Last active March 28, 2019 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mppfiles/85c7609d9eeb74e4b6e02f1b91157162 to your computer and use it in GitHub Desktop.
Save mppfiles/85c7609d9eeb74e4b6e02f1b91157162 to your computer and use it in GitHub Desktop.
Angular copy objects example
Ejemplo de cómo transformar una estructura de datos en instancias de objetos (copiando propiedades + métodos).
import { Component } from '@angular/core';
import { Person } from './Person';
import { Pet } from './Pet';
@Component({
selector: 'example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
testing() {
const raw_data = [
{ pet_name: 'Ollie', owner: { name: 'John Doe' } },
{ pet_name: 'Bob', owner: { name: 'Marcus Doe' } },
];
const all_pets: Pet[] = new Pet().fromList(raw_data);
console.dir(all_pets);
}
}
export abstract class Model {
fromList(src: any, extra?: any) {
const res = [];
for (const item of src) {
res.push(this.fromObject(Object.assign(item, extra)));
}
return res;
}
fromObject(src: any) {
const obj = Object.create(this);
return Object.assign(obj, src);
}
}
import { Model } from './Model';
export class Person extends Model {
name: String = null;
}
import { Model } from './Model';
import { Person } from './Person';
export class Pet extends Model {
pet_name: String = null;
owner: Person = null;
fromObject(src) {
src = super.fromObject(src);
src.owner = new Person().fromObject(src.person);
return src;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment