0

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?

3
  • new Date(userAccountInformation.creationDate)? Commented Oct 11, 2017 at 8:10
  • I'm looking for a general solution for all the objects that I receive from the server from all the different services. this was only an example. Commented Oct 11, 2017 at 8:13
  • Take a look at this question - I think it's a more general version of yours. The same problem as with Date you will experience with other custom classes. Commented Oct 11, 2017 at 8:54

1 Answer 1

1

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)
…}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response, but I'm looking for a general solution to support this problem in the app scope for each http request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.