When working with Angular Reactive forms, I encountered an issue while sending the form.value
data to an asp.net web-api. The code snippet includes a custom class called len
, which emulates a simplified version of a TimeSpan
.
Here is an example of my request:
{
"id": "a7b06cf9-36a5-4c7a-99e5-8b9661469329",
"minCapacity": 5,
"maxCapacity": 10,
"len": {
"Days": 0,
"Hours": 2,
"Minutes": 0
},
}
The default behavior of .NET TimeSpan
necessitates an input format like this:
string.Format("{0}.{1}:{2}:{3}", len.Days, len.Hours, len.Minutes, len.Seconds)
Otherwise, the variable len
registers as null.
To address this, I created an override method toString()
for my custom TimeSpan
class. However, even after utilizing the HTTP class in my Typescript
code, the object persists in JSON format.
Despite scouring through Stack Overflow and Google, I have not been able to find a solution yet. Any guidance on how to handle this at the client side
would be highly appreciated.
component.ts
saveItem(model: Room) {
let selected = this.selected;
this.roomService.createUpdateRoom(model).subscribe(
response => {
Helpers.setLoading(false);
var result = response as ServiceResult<any>;
if (result.hasError) {
this.toaster.error(result.message, 'Error');
}
else {
alert('ok');
this.viewForm();
}
},
error => {
this.toaster.error(error.message, 'Error');
});
}
service.ts
createUpdateRoom(request) {
return this.post('api/v1.0/room/createupdate', true, request);
}
base.service.ts
post(apiAddress: string, isAuthorizeRequest: boolean, parameter: any): Observable<any> {
return this.intercept(this.injector.get(AuthHttp).post(this.baseUrl + apiAddress, parameter).map(
(response) => {
let data = response.json();
if (data) {
httpSuccess = data;
}
return httpSuccess;
}
));
}
timespan.ts
export class TimeSpan {
day: number = 0;
hour: number = 0;
minute: number = 0;
toTimeString(): string {
return this.hour +':' + this.minute;
}
toString = (): string => {
return this.day + ':' + this.toTimeString() + ':00';
}
}
room.ts
export class Room {
id: string;
minCapacity: number;
maxCapacity: number;
len: TimeSpan;
}