[英]Convert JSON to Typescript Interface including Date method
在 Angular 7 上,我有以下 Post 模型:
export interface PostModel {
id: number;
created: Date;
published: boolean;
title: string;
}
我有以下 Angular 服务方法来获取帖子:
public getPosts(): Observable<PostModel[]> {
return this.httpClient.get<PostModel[]>(url).pipe(
map((post: PostModel)) => {
return {
id: post.id,
created: new Date(post.created),
published: post.published,
title: post.title
};
})
};
我正在手动将 API 响应转换为PostModel
...
这是因为created
类型是日期,而 Angular 不会自动转换它。
我想在我的代码的不同部分重用映射代码:
map((post: PostModel)) => return mapPostFromJson(post));
我可以将 PostModel 转换为类并将 mapPostFromJson 作为其方法。
但我更喜欢PostModel
继续作为一个接口。
我怎样才能做到这一点?
更新
我的问题是如何创建 mapPostFromJson 方法。 我试过:
mapPostFromJson(data: any) : PostModel {
return map((post: PostModel) => {
return {
id: post.id,
created: new Date(post.created),
published: post.published,
title: post.title
};
});
}
该函数不编译...
我不确定如何在管道外使用地图...
我不确定我是否正确理解了您的问题,但是,该映射函数会起作用吗?
mapPostFromJson(data: any): PostModel {
return {
id: data.id,
created: new Date(data.created),
published: data.published,
title: data.title
};
}
否则,使用函数式原则,您可以通过定义可重用于构建映射器的通用函数来制定更通用的解决方案:
// This function takes a structure of functions, and applies
// them to some data, returning a structure of the results
const mapper = functions => json => Object.entries(json)
.map(([k, val]) => ({ [k]: (functions[k] || (x => x))(val) }))
.reduce((acc, o) => Object.assign(acc, o), { });
然后,您可以轻松创建一个映射器并在您的 JSON 上调用它:
// create a mapper that passes all properties
// but transforms 'created' to a date
const mapPostFromJson = mapper({
created: x => new Date(x)
});
const post = mapPostFromJson(jsonPost);
使用此映射器,所有 JSON 属性都将通过,但创建的字段将转换为日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.