我正在研究這個項目,我需要將angular1的服務重寫爲angular2。將angularJS服務重寫爲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;
}]);
我寫的等值angular2像這樣:
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');
}
}
但我不能弄清楚如何使用http2providers在angular2即PUT,DELETE和POST請求,即我不dont知道如何在angular2中編寫剩餘的函數來執行所需的操作。
我嘗試了多個博客,但找不到解決方案。
我只想知道如何在angular2中編寫等效服務。
@i已經使用FET,發佈,刪除,但認沽我也需要通過object.but其不接受對象作爲參數如。 'updateWorkspace(workspace_id:string,workspace:Object,baseUrl:string){ return this.http.put(baseUrl +'/ pm/workspaces /'+ workspace_id,workspace) .map((res:Response)=> res。 。JSON())趕上(this.handleError); }' –
答案中增加了一些更多詳細信息 – Picci