I have implemented observables to fetch data in my Angular 2 application. Currently, multiple services/components are performing similar tasks. Therefore, I am looking to refactor the code to make it more efficient by passing a single parameter that varies in each API call made by the components. This way, I can use a single service for all the components requiring this functionality.
First, let me demonstrate what is currently functioning correctly:
In my service, I had the following implementation:
getByCategory() {
this._url = "https://api.someurl.com/v0/contacts/group/staff?limit=15&apikey=somekey";
return this._http.get(this._url)
.map((response: Response) => response.json())
.catch(this._errorsHandler);
}
_errorsHandler(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
And in my component, I was subscribing to this service like so:
this.contactService.getByCategory()
.subscribe(resRecordsData => this.records = resRecordsData,
responseRecordsError => this.errorMsg = responseRecordsError);
All of the above code is currently functional.
However, since the only difference between calls from different components is a single parameter (group) in the API call, I want to refactor the code to achieve something like this:
getByCategory(group) {
const q = encodeURIComponent(group);
this._url = `https://api.someurl.com/v0/contacts/group/${q}?limit=15&apikey=somekey`;
return this._http.get(this._url)
.map((response: Response) => response.json())
.catch(this._errorsHandler);
}
_errorsHandler(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
Then, in the components, I would subscribe to this service while also passing the specific group parameter unique to each component like this:
this.contactService.getByStage('staff')
.subscribe(resRecordsData => this.records = resRecordsData,
responseRecordsError => this.errorMsg = responseRecordsError);
When I attempt this modification, there are no errors thrown, but no data is being displayed in the view either. Is there something missing in the conversion of this function?