Skip to content

Instantly share code, notes, and snippets.

@owrrpon
Created June 5, 2021 17:18
Show Gist options
  • Save owrrpon/6f623686c98f76027a99fcdd9ff1f420 to your computer and use it in GitHub Desktop.
Save owrrpon/6f623686c98f76027a99fcdd9ff1f420 to your computer and use it in GitHub Desktop.
Adding the loader logic in the serviceWrapper() function in global utility service so that it is taken care of automatically for all service calls.
serviceWrapper(
HTTP_method: string,
API_URL: string,
responseProcessing: any,
request_data?: any,
skip_loading_animation?: boolean
): Subject<any> {
let response_subject = new Subject<any>();
// If it has not been explicitly mentioned to not show the loader, please show.
if(!!!skip_loading_animation){
this.globals.ongoing_request_count ++;
this.globals.loading_animation_control.next(true);
}
// For local API requests, fetch the JSON file instead
if(!environment.production){
HTTP_method = 'GET';
API_URL += '.json';
}
this.http.request(
HTTP_method,
API_URL,
request_data
).pipe(
finalize(
() => {
if(!!!skip_loading_animation){
if(this.globals.ongoing_request_count > 0){
this.globals.ongoing_request_count --;
}
// Hiding the loading animation
this.globals.loading_animation_control.next(false);
}
}
)
).subscribe(
(response: any) => {
// If this is an error object directly send it across
if(!!response['errorCode']){
response_subject.error(response);
}else{
let processed_response = responseProcessing(response);
if(!!processed_response.error){
response_subject.error(processed_response.error);
}else{
response_subject.next(processed_response.data);
}
}
},
(error) => {
let error_object = {
'message' : this.error_messages.service_failure
};
response_subject.error(error_object);
}
);
return response_subject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment