作者:希望全家人都幸福_870 | 来源:互联网 | 2023-10-10 07:51
ImtryingtomakeaclassPostcontainspostattributessuchasid,title,contentetc.我正在尝试创建
I'm trying to make a class Post contains post attributes such as "id, title, content ...etc.
我正在尝试创建一个类Post包含帖子属性,如“id,title,content ...等。
I want to initialize the class from a JSON response. I'm using angular-http to get JSON in typescript
我想从JSON响应初始化类。我正在使用angular-http来获取打字稿中的JSON
in APP.TS:
在APP.TS:
class AppComponent {
result: { [key: string]: string; };
map: Map;
constructor(http: Http) {
http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => {
this.result = res.json();
this.map = res.json();
console.log(this.result);
console.log(this.map);
});
}
}
note: I'm still confused about which is the right type for my JSON I read that typescript is not supporting Map yet, however it is working here as result: {[key:string]: string; };
注意:我仍然感到困惑的是我的JSON哪个是正确的类型我读过打字稿不支持Map,但是它在这里工作:{[key:string]:string; };
I tried to look up on stackoverflow, I found this question how to cast a json object to a typescript, the answer has nothing to do with typescript.
我试着查看stackoverflow,我发现这个问题如何将一个json对象转换为打字稿,答案与打字稿无关。
in another question Can I create a TypeScript type and use that when AJAX returns JSON data?
在另一个问题中我可以创建一个TypeScript类型并在AJAX返回JSON数据时使用它吗?
the answer is talking about creating interfaces in typescript. (which I didn't quite understand it.)
答案是谈论在打字稿中创建接口。 (我不太明白。)
I also found this site for json2ts generates typescript interfaces from JSON, so I tried my json and I got this:
我还发现json2ts的这个站点从JSON生成typescript接口,所以我尝试了我的json,我得到了这个:
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've got a typescript interface for my JSON, but I don't know what to do next!
现在我的JSON有一个打字稿界面,但我不知道下一步该做什么!
Q: Is this the right way to parse JSON to a class object in typescript? if yes what is the next step to get the class initialized with the data?
问:这是将JSON解析为打字稿中的类对象的正确方法吗?如果是,使用数据初始化类的下一步是什么?
1 个解决方案