[英]Rewriting angularJS services to angular2
我正在從事這個項目,我需要將服務從angular1重寫為angular2。
對於前。
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');
}
}
但是我無法弄清楚如何使用angular2中的http_providers發出PUT,DELETE和POST請求,即我不知道如何在angular2中編寫剩余的函數來執行所需的操作。
我嘗試了多個博客,但找不到解決方案。
我只想知道如何在angular2中編寫等效的服務。
Angular2 http客戶端除了get方法(您在代碼中使用的方法)之外,還公開了post,put和delete方法。 您需要使用此類方法來實現其他操作。
希望對您有所幫助
每個評論的更多詳細信息
這是一段代碼,顯示了如何使用http PUT。
let myUrl = this._environment.baseRestServicesUrl + serviceIdentifier;
let options = this.getOpionsForPost();
let jsonString = JSON.stringify(inProduct);
return this._http.post(myUrl, jsonString, options)
.catch(this.handleError);
和
private handleError (error: Response) {
return Observable.throw(JSON.stringify(error));
}
private getOpionsForPost() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return new RequestOptions({headers: headers});
}
import {Headers, Http, Response} from 'angular2/http';
public Foo(params: Object, data: string) {
let url: string = 'String Url path'
// Eg for post
return this.http.post(url, data, {headers: this.jsonHeaders}).map((res: Response) => res.json());
// Eg for delete
return this.http.delete(url, {headers: this.jsonHeaders});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.