Skip to content

Instantly share code, notes, and snippets.

@mppfiles mppfiles/.Angular Model Copy Secret
Last active Mar 28, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.