[英]Convert JSON to Typescript Interface including Date method
On Angular 7 I have the following Post Model:在 Angular 7 上,我有以下 Post 模型:
export interface PostModel {
id: number;
created: Date;
published: boolean;
title: string;
}
And I have the following Angular service method to get posts:我有以下 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
};
})
};
I am converting the API response to PostModel
manually ...我正在手动将 API 响应转换为PostModel
...
This is because created
type is Date and Angular does not converts it automatically.这是因为created
类型是日期,而 Angular 不会自动转换它。
I would like to reuse the mapping code in different parts of my code:我想在我的代码的不同部分重用映射代码:
map((post: PostModel)) => return mapPostFromJson(post));
I could convert PostModel to class and mapPostFromJson as its method.我可以将 PostModel 转换为类并将 mapPostFromJson 作为其方法。
But I would prefer PostModel
to keep being an interface.但我更喜欢PostModel
继续作为一个接口。
How can I do this?我怎样才能做到这一点?
Update更新
My problem is how to create the mapPostFromJson method.我的问题是如何创建 mapPostFromJson 方法。 I tried:我试过:
mapPostFromJson(data: any) : PostModel {
return map((post: PostModel) => {
return {
id: post.id,
created: new Date(post.created),
published: post.published,
title: post.title
};
});
}
This function does not compile ...该函数不编译...
I am not sure how to use map outside pipe ...我不确定如何在管道外使用地图...
I am not sure I understand your question correctly, but, would that mapping function work?我不确定我是否正确理解了您的问题,但是,该映射函数会起作用吗?
mapPostFromJson(data: any): PostModel {
return {
id: data.id,
created: new Date(data.created),
published: data.published,
title: data.title
};
}
Otherwise, using functional principles, you could make a more generic solution by defining general functions that you can reuse to build your mappers:否则,使用函数式原则,您可以通过定义可重用于构建映射器的通用函数来制定更通用的解决方案:
// 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), { });
You can then easily create a mapper and call it on your JSON:然后,您可以轻松创建一个映射器并在您的 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);
Using this mapper, all JSON properties will pass through, but the created field will be transformed to a date.使用此映射器,所有 JSON 属性都将通过,但创建的字段将转换为日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.