Skip to content

Instantly share code, notes, and snippets.

@afmicc
Last active September 27, 2018 20:59
Show Gist options
  • Save afmicc/d63c813885089e31666c6f419a9c3094 to your computer and use it in GitHub Desktop.
Save afmicc/d63c813885089e31666c6f419a9c3094 to your computer and use it in GitHub Desktop.
Convert json response to object in typescript
import { CopyHelper } from '../../helpers/copy.helper';
import { Area } from '../../models/area';
export class AreaListComponent
{
...
getAreas(): void
{
this.service.getAll()
.subscribe(response =>
{
this.apiErrors = false;
this.apiErrorsMessage = "";
if (response)
this.source = CopyHelper.toArray(Area, response);
},
error =>
{
this.apiErrors = true;
this.apiErrorsMessage = error._body;
});
}
}
export class Area
{
id: number = 0;
name: string = "";
}
export class CopyHelper
{
public static toArray<T>(t: {new(): T; }, oldValues: any): Array<T>
{
let values = new Array<T>();
for (const old of oldValues)
values.push(this.toObject(t, old));
return values;
}
public static toObject<T>(t: {new(): T; }, oldValue: any): T
{
var newValue = Object.assign(new t(), oldValue);
return newValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment