I'm facing a scenario where my Angular service retrieves values from an HTTP GET request and maps them to an Observable object of a specific type. Sometimes, one of the properties has a string value, while other times it's null, which I want to default to an empty string.
Is there a more elegant solution for this issue than the current approach I'm using?
I have attempted passing a boolean parameter for the specific field of interest, in this case, template.AreaId attribute. However, I am worried that as more attributes encounter similar problems over time with the creation of more template objects.
getTaskFromTemplate(extraChildTask:string, hasArea: boolean) : Observable<Task>{
if (hasArea){
return this.templateService.getTemplateByName(extraChildTask).pipe(
map(template => {
return {
WorkItemId:'',
WorkItemType:'Task',
Title: template.Title,
Description: template.Description,
AssignedTo: '',
TeamProject: template.TeamProjectName,
AreaPathId: template.AreaId ? template.AreaId.toString() : '',
IterationPathId: '',
Application:'',
State:'',
TargetDate: null,
OriginalEstimate: 0,
CompletedWork: 0,
RemainingWork: 0,
BusinessPriority: '',
CreatedBy:'',
CreatedDate: null,
Priority:'',
Notes:'',
AreaPathName:'',
IterationPathName:'',
};
}),
catchError((error: HttpErrorResponse) => { return throwError(error); })
)
}
return this.templateService.getTemplateByName(extraChildTask).pipe(
map(template => {
return {
WorkItemId:'',
WorkItemType:'Task',
Title: template.Title,
Description: template.Description,
AssignedTo: '',
TeamProject: template.TeamProjectName,
AreaPathId: '',
IterationPathId: '',
Application:'',
State:'',
TargetDate: null,
OriginalEstimate: 0,
CompletedWork: 0,
RemainingWork:0,
BusinessPriority: '',
CreatedBy:'',
CreatedDate: null,
Priority:'',
Notes:'',
AreaPathName:'',
IterationPathName:'',
};
}),
catchError((error: HttpErrorResponse) => { return throwError(error); })
)
}
}
The above implementation is functional, but I seek a more efficient way to handle cases where a field is null or lacks a string value.
Here is how I initially structured the code before encountering issues with the null value of template.AreaId:
getTaskFromTemplate(extraChildTask:string) : Observable<Task>{
return this.templateService.getTemplateByName(extraChildTask).pipe(
map(template => {
return {
WorkItemId:'',
WorkItemType:'Task',
Title: template.Title,
Description: template.Description,
AssignedTo: '',
TeamProject: template.TeamProjectName,
AreaPathId: template.AreaId ? template.AreaId.toString() : '',
IterationPathId: '',
Application:'',
State:'',
TargetDate: null,
OriginalEstimate: 0,
CompletedWork: 0,
RemainingWork: 0,
BusinessPriority: '',
CreatedBy:'',
CreatedDate: null,
Priority:'',
Notes:'',
AreaPathName:'',
IterationPathName:'',
};
}),
catchError((error: HttpErrorResponse) => { return throwError(error); })
)
}