I am developing an Angular 2 application where I have some services (Angular 2 service) that communicates to my server side methods through HTTP calls. I am calling the services in components to get the data and display them on the views. This is working fine but I have written separate services for separate data operations. For example I have a Dashboard where I am loading a list of tasks, so for that I have a loadTask method in my component as follows --
public loadTask() {
console.log('Component : Dashboard Component - Method : loadTask');
//Get the current user
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.taskListBusy = this._dashboardService.getTaskList(currentUser.EmployeeId).subscribe(
data => this.taskListItems = data,
error => this._errorLoggerService.logError(error, 'Dashboard/TaskList Component'),
() => console.log("Task List For User Id - " + this._userLoginService.getCurrentUserId() + "\n" + JSON.stringify(this.taskListItems)));
}
This method is calling a service method i.e.
this._dashboardService.getTaskList(currentUser.EmployeeId)
where _dashboardService.getTaskList() is a service method as follows --
public getTaskList(userId: any): Observable<TaskListModel[]> {
console.log('Service - DashboardService : Method - getTaskList : Params - ' + userId);
let postData = "userId=" + userId;
this._requestOptions = new RequestOptions({
method: RequestMethod.Post,
url: this._httpHelperService.apiUrl + 'Dashboard/getTaskListByUserId',
headers: this._httpHelperService.contentTypeJson,
body: JSON.stringify({ 'userId': userId })
});
console.log('Get Task List - POST Request Query : ' + JSON.stringify(this._requestOptions));
return this._http.request(new Request(this._requestOptions)).map(this._httpHelperService.extractData).catch(this._httpHelperService.handleError);
}
As you can see it is doing nothing but making a http call to get the data. All I want is a generic service that will do all my HTTP calls. It should be such that I will pass the controller name, method name and parameters and then it should make the http call to get the data. Is there a way I can do this ?
getTaskList?http servicefrom@angular/httpis already a generic service for doing http. But if you need to wrap it for all your calls, then go ahead. Usually you want to do different things for different data, and the http service is usually abstracted enough