我试图使一个类 post 包含post属性,例如"id、title、content...etc“。
我想从JSON响应初始化这个类。我正在使用角-http获取类型记录中的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的哪种类型感到困惑--我读到,类型记录还不支持Map,但是它作为result: {[key:string]: string; };在这里工作
我试图查找堆叠溢出,我发现这个问题如何将json对象强制转换为类型记录,答案与类型记录无关。
在另一个问题中,我可以创建一个TypeScript类型并在AJAX返回JSON数据时使用它吗?
答案是讨论如何在类型记录中创建接口。(我不太明白。)
我还找到了一个用于json2ts的站点,它可以从json生成类型记录接口,所以我尝试了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 :这是在类型记录中将解析为类对象的正确方法吗?如果是,那么使用数据初始化类的下一步是什么呢?
发布于 2015-11-20 17:18:39
您绝对应该使用接口来描述DTO (数据传输对象)。看起来,json2ts在描述JSON结构方面做得很好。现在,因为http服务为您创建了对象,所以您不必创建一个新的对象.您只需将其转换到您的界面,如下所示:
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.https://stackoverflow.com/questions/33831711
复制相似问题