I am trying to create a Post class containing message attributes such as "id, title, content ... etc.
I want to initialize a class from a JSON response. I use angular -http to get JSON in typescript
in APP.TS:
class AppComponent { result: { [key: string]: string; }; map: Map<Object,Object>; constructor(http: Http) { http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => { this.result = <any>res.json(); this.map = <any>res.json(); console.log(this.result); console.log(this.map); }); } }
Note: I'm still confused about which type is correct for my JSON. I read that typescript does not support Map , but it works here as result: {[key:string]: string; }; result: {[key:string]: string; };
I tried looking at stackoverflow, I found this question how to pass a json object to typescript , the answer has nothing to do with typescript.
in another question Can I create a typescript type and use it when AJAX returns JSON data?
the answer is about creating interfaces in typescript. (which I did not quite understand).
I also found this site for json2ts to create typescript interfaces from JSON, so I tried my json and I got this:
declare module namespace { export interface Guid { rendered: string; } export interface Title { rendered: string; } export interface Content { rendered: string; } export interface Excerpt { rendered: string; } export interface Self { href: string; } export interface Collection { href: string; } export interface Author { embeddable: boolean; href: string; } export interface Reply { embeddable: boolean; href: string; } export interface VersionHistory { href: string; } export interface Links { self: Self[]; collection: Collection[]; author: Author[]; replies: Reply[]; } export interface RootObject { id: number; date: Date; guid: Guid; modified: Date; modified_gmt: Date; slug: string; type: string; link: string; title: Title; content: Content; excerpt: Excerpt; author: number; featured_image: number; comment_status: string; ping_status: string; sticky: boolean; format: string; _links: Links; } }
Now I have a typescript interface for my JSON, but I don't know what to do next!
Q: Is this the correct JSON parsing for a class object in typescript? if so, what is the next step to get the data initialized class?
source share