转换JSON到打字稿接口,包括日期方法

问题描述 投票:-2回答:1

在角7我有以下邮政型号:

export interface PostModel {
  id: number;
  created: Date;
  published: boolean;
  title: string; 
}

我有以下的角服务方法来获得职位:

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类型是日期和角度不会自动将其转换。

我想重用我的代码不同部分映射代码:

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
    };

  });

}

此功能不会编译...

我不知道如何使用地图外管...

angular typescript angular6 angular7
1个回答
1
投票

我不知道我正确理解你的问题,但是,是否会映射功能的工作?

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属性将通过,但创造了场将被改造为一个日期。

© www.soinside.com 2019 - 2024. All rights reserved.