Sample RESTful service for use with Angular 2:
import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import 'rxjs/add/operator/map' import { Observable } from 'rxjs/Observable'; /* database User table structure: ID INTEGER NOT NULL, AUTOINCREMENT NAME VARCHAR(50) NOT NULL PHONE VARCHAR(20) NOT NULL */ export class User { public id:number; public name:string; public phone:string; } @Injectable() export class UserService { private actionUrl: string; private headers: Headers; // // sample url for a web service ==> "http://somesite.com/user/" // constructor(private http: Http, url:string) { this.actionUrl = url; this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); this.headers.append('Accept', 'application/json'); } public GetUsers = (): Observable<Response> => { return this.http.get(this.actionUrl).map(res => res.json()); } public GetUser = (id: number): Observable<Response> => { return this.http.get(this.actionUrl + id).map(res => res.json()); } public InsertUser = (user: User): Observable<Response> => { var toAdd = JSON.stringify({ User: user }); return this.http.post(this.actionUrl, toAdd, { headers: this.headers }).map(res => res.json()); } public UpdateUser = (id: number, itemToUpdate: User): Observable<Response> => { return this.http.put(this.actionUrl + id, JSON.stringify(itemToUpdate), { headers: this.headers }).map(res => res.json()); } public DeleteUser = (id: number): Observable<Response> => { return this.http.delete(this.actionUrl + id); } }