Sajeetharan
Sajeetharan

Reputation: 222522

Angular service code refactoring

I have followed this format in my application to communicate with API and fetch data from it.

Following is the code from one of the service.ts

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);
} 

Now we are using cpd to detect the code duplication in the application and it complains that wherever i am using extractData and handleErrors code is duplicated.

Is there a better way to handle this using base class?

Upvotes: 0

Views: 225

Answers (1)

yurzui
yurzui

Reputation: 214007

You can move your methods to base class something like:

class BaseService {
  constructor(
    private http: Http, 
    @Inject(AppConfig) private appConfig: AppConfig) {}

  get(url: string) {
     return this.http
            .get(`${this.appConfig.getAPIUrl()}${url}`)
            .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);
  }
}

class DetailsService extends BaseService {
  getCheckoutDetails() {
    let query = '7668';
    return this.get(`/buy/getDetails?${query}`) }
}

Upvotes: 1

Related Questions