0

I have an Angular WebApp who retrives data from a backend Java server via http get. Example:

public getStateForUser(): Observable<UserRegistrationState> {
   return this.http.get<any>(Environment.getServerAddress() + '/' + 
   UserRegistrationStateService.SERVICE_URL + '/getStateForUser', {
      params: {
        sessionIdentityStr: this.authGuard.getSession().sessionIdentityStr
      }
   });
}

export class UserRegistrationState {
  registerDate: Date;
  emailVerified: boolean;
  unlocked: boolean;
}

This works fine for all fields. Except the Dates. The Dates are not parsed correctly, so I want to add a custom parser where I can tell him how he gets the date value from the json date string.

Of course now I can add a custom Parser for the whole UserRegistrationState class, but I have Dates on multiple classes and I do not want to create a Parser for every class, because the other properties(except the Dates) are parsed fine.

So my question: Is there a way to add a custom parser for all Date fields?

P.S. This is an example JSON date string, automatically parsed from a Java LocalDateTime:

"registerDate":{"dayOfMonth":17,"dayOfWeek":"WEDNESDAY","dayOfYear":290,"month":"OCTOBER","monthValue":10,"year":2018,"hour":21,"minute":21,"nano":370000000,"second":16,"chronology":{"id":"ISO","calendarType":"iso8601"}}
2
  • Wouldn't it be easier to format and send the date as a string of milliseconds since epoch and use a date pipe to get the format you need? Commented Oct 17, 2018 at 20:11
  • Tell the author of that Java backend server to learn about the ISO 8601 standard. These standard text formats are supported by default in the java.time classes. Commented Oct 18, 2018 at 0:24

1 Answer 1

1

This unfriendly date format is probably caused by backend. I never had any problems with dates from any API in Angular.

You can create getters/setters to encapsulate custom parsing logic for some field in your class.

In my opinion would be better to fix backend side and move from classes to interfaces in Angular side. Interfaces are better for plain DTO models in TypeScript.

Sign up to request clarification or add additional context in comments.

Comments

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.