我正在尝试使一个类Post包含帖子属性,例如“id、title、content… etc.
我想从JSON响应中初始化类。我正在使用角度超文本传输协议来获取打字稿中的JSON
在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);
});
}
}
注意:我仍然不知道哪个类型适合我的JSON我读到typescript还不支持Map,但是它在这里作为结果工作:{[key: string]:string;};
我试图在stackoverflow上查找,我发现这个问题如何将json对象转换为typescript,答案与typescript无关。
在另一个问题中,我可以创建一个TypeScript类型并在AJAX返回JSON数据时使用它吗?
答案是关于在typescript中创建接口。(我不太明白。)
我还发现了这个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;
}
}
现在我有了JSON的打字界面,但我不知道下一步该怎么办!
问:这是正确的方法来解析JSON一个类对象在typecript?如果是什么是下一步得到类初始化的数据?
你绝对应该使用接口来描述你的DTO(数据传输对象)。看起来json2ts在描述你的JSON结构方面做得很好。现在,因为超文本传输协议服务为你创建了对象,你不必创建一个新的…你只需要将它转换到你的接口,如下所示:
class AppComponent {
dataFromServer : RootObject;
http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => {
this.dataFromServer = <RootObject>res.json();
});
}
从那时起,TypeScript将保护您在尝试访问来自服务器的任何数据时不犯任何错误。例如:
this.dataFromServer.age = 45; // Error: age doesn't exist in the RootObject interface
this.id = "Hello"; // Error, id was is a number, and you try to put string into it.
this.id = 100; // will be just fine.