Tal Humy
Tal Humy

Reputation: 1227

Angular 4 - Convert date string to object for each server entity

What is the best way to implement a conversion from date string to date object for each service the request data from server? Lets say I have a userService that fetch some users from database. each user implements this interface :

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

But when receiving the user on the client the creationDate is a string and not an object. I know it can be changed from the service, but I wonder if there is a general solution for all services using maybe a regex on the request response? Is this a good idea to use something like that?

Upvotes: 0

Views: 534

Answers (1)

G.Vitelli
G.Vitelli

Reputation: 1287

Possible 'clean' solution with 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: '[email protected]',
  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: "[email protected]", companyName: "companyname", phoneNumber:                 "+000", firstName: "firstname", 
creationDate: Sun Jan 01 2017 01:00:00 GMT+0100 (W. Europe Standard Time)
…}

Upvotes: 1

Related Questions