In my application, I have implemented this specific format to interact with an API and retrieve data from it.
Below is the code snippet taken from one of the service.ts files:
getCheckoutDetails(): Observable<UserDetail> {
let query = `7668`;
return this.http
.get(this.appConfig.getAPIUrl()
+ `/buy/getDetails?${query}`)
.map(this.extractData)
.catch(this.handleErrors);
}
private extractData(res: Response) {
let data = res.json();
return data.body ? data.body.message ? data.body.message : {} : {};
}
private handleErrors(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
We are now utilizing cpd
to identify duplicated code in the application. Interestingly, it points out that there is duplication whenever the methods extractData
and handleErrors
are utilized.
Is there a more efficient approach to address this issue by employing a base class?