I have a rest-provider service that has all of my http calls. However, each function is reusing a lot of the same http code and it seems like I should be wrapping this into a shared function incase I want to change anything in it
As you can see the 2 functions are almost exactly the same with just the url changing. How do I refactor this code to not reuse the same code in all my functions?
getStepMenu(_params): Observable<StepMenu> {
// Add params
let params = new HttpParams();
for (let key in _params) {
if (_params.hasOwnProperty(key)) {
params = params.set(key, _params[key]);
}
}
return this.http
.get<StepMenu>(this.env.API_URL 'api/step_menu', { headers: this.headers, params: params })
.pipe(
retry(this.retries),
catchError(this.handleError)
)
}
getStepInfo(_params): Observable<StepInfo> {
// Add params
let params = new HttpParams();
for (let key in _params) {
if (_params.hasOwnProperty(key)) {
params = params.set(key, _params[key]);
}
}
return this.http
.get<StepInfo>(this.env.API_URL 'api/step_info', { headers: this.headers, params: params })
.pipe(
retry(this.retries),
catchError(this.handleError)
)
}
CodePudding user response:
The only difference I see is the api path, you can just pass it as an method argument as follows:
getStepMenu(_params): Observable<StepInfo> {
return this.callStepApi('api/step_menu', _params)
}
getStepInfo(_params): Observable<StepInfo> {
return this.callStepApi('api/step_info', _params);
}
callStepApi(path, _params): Observable<StepInfo> {
// Add params
let params = new HttpParams();
let url = this.env.API_URL path;
for (let key in _params) {
if (_params.hasOwnProperty(key)) {
params = params.set(key, _params[key]);
}
}
return this.http
.get<StepInfo>(url, { headers: this.headers, params: params })
.pipe(
retry(this.retries),
catchError(this.handleError)
)
}
You can invoke it the same way by subscribing to the obserables returned:
getStepInfo(params).subscribe();
getStepMenu(params).subscribe();