Last active
September 27, 2018 20:59
-
-
Save afmicc/d63c813885089e31666c6f419a9c3094 to your computer and use it in GitHub Desktop.
Convert json response to object in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Area | |
{ | |
id: number = 0; | |
name: string = ""; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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