I am working on this project in which I need to rewrite services from angular1 to angular2.
for ex.
pm.service.js(angularJS)
angular.module('projects').factory('ProjectsService', ['$resource', function ($resource) {
var data = $resource('/pm/projects/:id/:action', {id: '@id', action: '@action'}, {
getAllProjects: {method: 'GET', isArray: true, interceptor: {response: function (response) {
return response.data;
}}},
getProjectById: {method: 'GET', params: {id: '@id'}, isArray: true, interceptor: {response: function (response) {
return response.data;
}}},
saveProject: {method: 'POST', interceptor: {response: function (response) {
return response.data;
}}},
updateProject: {method: 'PUT', interceptor: {response: function (response) {
return response;
}}},
deleteProject: {method: 'DELETE', interceptor: {response: function (response) {
return response;
}}},
exportProject: {method: 'POST', params: {id: '@id', action:'@action'} , interceptor: {response: function (response) {
return response.data;
}}}
});
return data;
}]);
I wrote its equivalent in angular2 Like this:
pm.service.ts(angular2)
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ProjectsService {
constructor(private http: Http) { }
getAllProjects(baseUrl:string) {
return this.http.get(baseUrl+'/pm/projects/')
.map((res: Response) => res.json()).catch(this.handleError);
}
getProjectById(id:string,baseUrl:string){
return this.http.get(baseUrl+'/pm/projects/'+id)
.map((res: Response) => res.json()).catch(this.handleError);
}
handleError(error: any) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
But I cant figure out how to make PUT,DELETE and POST requests using http_providers in angular2 i.e. I dont know how to write remaining functions in angular2 which will perform the required operations.
I tried multiple blogs but couldn't find the solution.
I would just like to know How to write equivalent services in angular2.