Angular 4 - 将日期字符串转换为每个服务器实体的对象

时间:2017-10-11 08:08:35

标签: angular

从服务器请求数据为每个服务实现从日期字符串到日期对象的转换的最佳方法是什么? 假设我有一个userService从数据库中获取一些用户。每个用户都实现了这个接口:

export interface UserAccountInformation {
  id: string,
  email: string,
  companyName?: string,
  phoneNumber?: string,
  firstName?: string,
  lastName?: string,
  country?: string,
  zipCode?: string,
  creationDate: Date
}

但是当在客户端上接收用户时,creationDate是一个字符串而不是一个对象。我知道它可以从服务中更改,但我想知道是否有一个通用的解决方案,所有服务使用可能正则表达式的请求响应? 使用类似的东西是个好主意吗?

1 个答案:

答案 0 :(得分:1)

使用RxJS可能的'干净'解决方案:

export interface UserAccountInformation {
  id: string,
  email: string,
  companyName?: string,
  phoneNumber?: string,
  firstName?: string,
  lastName?: string,
  country?: string,
  zipCode?: string,
  creationDate: Date
}

const response: any = {
  id: '1',
  email: 'test@test.com',
  companyName?: 'companyname',
  phoneNumber?: '+000',
  firstName?: 'firstname',
  lastName?: 'lastname',
  country?: 'country',
  zipCode?: 'zipcode',
  creationDate: '2017-01-01'
}

// replace Rx.Observable.of with Angular HTTP this.get('urlToCall')
Rx.Observable.of(response)
.map((response: any) => {
    response.creationDate = new Date(response.creationDate)
    //cast to UserAccountInformation interface
    return <UserAccountInformation>response;
})
.subscribe((userAccountInformation: UserAccountInformation) => {
    console.log(userAccountInformation);
});

Output:
{id: "1", email: "test@test.com", companyName: "companyname", phoneNumber:                 "+000", firstName: "firstname", 
creationDate: Sun Jan 01 2017 01:00:00 GMT+0100 (W. Europe Standard Time)
…}