title: Typescript generic service
body: <p>I'm new to typescript and angular2/4 and I'm building a single app that have two basic entities which is Car and Driver and all I do is to list them with an API call.</p>
  
  <p>The problem I'm facing is that I have code redundancy for each CarService and DriverService, and I might have the same code for other entities service.</p>
  
  <p>The implementation is following so far, skipping other methods for ilustration :</p>
  
  <pre><code>@Injectable()
  export class CarService  {
  
  private actionUrl: string;
  private headers: Headers;
  
  constructor(private _http: Http, private _configuration: Configuration) {
  
      // Getting API URL and specify the root
      this.actionUrl = _configuration.serverWithApiUrl + 'Car/';
  
      this.headers = new Headers();
      this.headers.append('Content-Type', 'application/json');
      this.headers.append('Accept', 'application/json');
  }
  
  // Function to get all Cars - API CALL: /
  public GetAll = (): Observable&lt;Car[]&gt; =&gt; {
      return this._http.get(this.actionUrl)
          .map((response: Response) =&gt; &lt;Car[]&gt;response.json())
          .catch(this.handleError);
  }
  
  // Function to get a Car by specific id - API CALL: /:id
  public GetSingle = (id: number): Observable&lt;Car&gt; =&gt; {
      return this._http.get(this.actionUrl + id)
          .map((response: Response) =&gt; &lt;Car&gt;response.json())
          .catch(this.handleError);
  }
  
  // Function to add a Car - API CALL: /create
  public Add = (newCar: Car): Observable&lt;Car&gt; =&gt; {
      return this._http.post(this.actionUrl + '/create', JSON.stringify(newCar), { headers: this.headers })
          .catch(this.handleError);
  }
  
  // Function to update a Car - API CALL: /
  public Update = (id: number, CarToUpdate: Car): Observable&lt;Car&gt; =&gt; {
      return this._http.put(this.actionUrl + id, JSON.stringify(CarToUpdate), { headers: this.headers })
          .catch(this.handleError);
  }
  
  // Function to delete a Car - API CALL: /:id
  public Delete = (id: number): Observable&lt;Response&gt; =&gt; {
      return this._http.delete(this.actionUrl + id)
          .catch(this.handleError);
  }
  
  // Function to throw errors
  private handleError(error: Response) {
      console.error(error);
      return Observable.throw(error.json().error || 'Server error');
  }
  </code></pre>
  
  <p>What only change with the DriverService is the <code>Car/</code> at the end of the url and the data type in <code>Observable&lt;Car[]&gt;</code> and the response.</p>
  
  <p>I would like to know what is the best way to avoid this with a generic service and how to do it in Typescript.</p>