I have followed this format in my application to call the API and get data from it:
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);
}
This is sample code on one service. Now this has been followed in all services to handle data and error. When I run gulp cpd command
to detect the duplicate code, it lists down all the files. Is there a way to handle this without duplicating?
1 Answer 1
Create one httpservice
and extend it in your service, for example:
HttpService:
export class HttpService {
protected userInfo:IUserModel;
constructor(public http: Http, public user: User) {
this.userInfo = this.user.getInfo();
}
/**
* method http get
* @param url
* @param params
* @returns {Http}
*/
fetch(url, params, addData) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('User-Id', this.userInfo.id);
headers.append('Token', this.userInfo.accessToken);
if(addData.accessType) {
headers.append('Access-Type', '1');
}
if(addData.limit) {
headers.append('Offset-Step', addData.limit);
}
if(addData.page || addData.page === 0) {
let count = (parseInt(addData.page )- 1) * parseInt(addData.limit);
headers.append('Count', count.toString());
}
let options = new RequestOptions(
{
headers: headers,
search: params,
});
return this.http
.get(
url,
options
)
.map(this.extractData)
.catch(this.handleErrors);
}
/**
* method http post
* @param url
* @param data
* @returns {Http}
*/
send(url, data) {
let body = JSON.stringify(data);
let headers = new Headers({
'Content-Type': 'application/json',
'User-Id': this.userInfo.id,
'Token': this.userInfo.accessToken
});
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body, options)
.map(this.extractData)
.catch(this.handleErrors);
}
/**
* method http put
* @param url
* @param data
* @returns {Http}
*/
stick(url, data) {
let body = JSON.stringify(data);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('User-Id', this.userInfo.id);
headers.append('Token', this.userInfo.accessToken);
return this.http
.put(url, body, {headers:headers})
.map(this.extractData)
.catch(this.handleErrors);
}
/**
* method http delete
* @param url
* @param params
* @returns {Http}
*/
remove(url, params) {
//var data = Object.keys(params).map(function(k) {
// return encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
//}).join('&');
//url += '?' + data;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('User-Id', this.userInfo.id);
headers.append('Token', this.userInfo.accessToken);
for(var i in params) {
headers.append(i, params[i]);
}
return this.http.delete(url, {headers:headers})
.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);
}
}
And in your child service extends by HttpService
:
export class SomeService extends HttpService {
constructor(private urls: Urls, http: Http, user: User) {
super(http, user);
}
getCheckoutDetails(data): Observable<UserDetail> {
let query = `7668`;
header = {};
return this.fetch(this.appConfig.getAPIUrl() + `/buy/getDetails?${query}`);
}
}
Maybe you need a correct HttpService
.