Within my Angular 7 project, there is a Post Model defined as follows:
export interface PostModel {
id: number;
created: Date;
published: boolean;
title: string;
}
I have implemented an Angular service method aimed at retrieving posts:
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
};
})
};
In the process of converting the API response to PostModel
, I discovered that the conversion for the created
type to Date does not happen automatically in Angular.
Desiring reusability for the mapping code across various sections of my application, I attempted:
map((post: PostModel)) => return mapPostFromJson(post));
Even though I could convert PostModel to a class and implement mapPostFromJson as its method, I am inclined to retain PostModel
as an interface.
The challenge lies in creating the mapPostFromJson method. My attempt looked like this:
mapPostFromJson(data: any) : PostModel {
return map((post: PostModel) => {
return {
id: post.id,
created: new Date(post.created),
published: post.published,
title: post.title
};
});
}
However, this function fails to compile. I am uncertain about how to utilize map outside of the pipe...