2016-06-20 20 views
5

Ho pochi servizi, che hanno lo stesso codice all'interno:Come estendere una classe in TypeScript?

constructor (private http: Http) { 
    //use XHR object 
    let _build = (<any> http)._backend._browserXHR.build; 
    (<any> http)._backend._browserXHR.build =() => { 
     let _xhr = _build(); 
     _xhr.withCredentials = true; 
     return _xhr; 
    }; 
} 

ho voluto spostare il codice al file separato http_base_clas.ts e di riutilizzare il codice il più possible.Here è http_base_clas.ts:

import {Http} from '@angular/http'; 

export class HttpBaseClass { 
    constructor (http: Http) { 
     //use XHR object 
     let _build = (<any> http)._backend._browserXHR.build; 
     (<any> http)._backend._browserXHR.build =() => { 
      let _xhr = _build(); 
      _xhr.withCredentials = true; 
      return _xhr; 
     }; 
    } 
} 

Come estendere http_base_class in auth_service.ts?

import {Injectable} from '@angular/core'; 
import {Http, Response} from '@angular/http'; 
import {Headers, RequestOptions} from '@angular/http'; 
import {Observable} from 'rxjs/Observable'; 

@Injectable() 

export class AuthenticationService { 
result: { 
    ok: boolean; 
}; 
private verifyUrl = 'http:example.com; 

constructor (private http: Http) { 

} 
private authRequest (url) { 
    let body = JSON.stringify({}); 
    let headers = new Headers({ 'Content-Type': 'application/json'}); 
    let options = new RequestOptions({ 
     headers: headers 
    }); 
    return this.http.post(url, body, options) 
     .map((res: Response) => res.json()) 
     .map(res => { 
      this.result = res; 
      return this.result.ok; 
     }); 
    } 
} 

risposta

6
class AuthenticationService extends HttpBaseClass { 
    constructor(http:Http) { 
    super(http); 
    } 

    private authRequest (url) { 
    ... 
    } 
} 
+0

grazie per aiuto. – Serhiy

+1

Il tuo nome è su ogni domanda angolare e la tua risposta non delude mai. Grazie! –

+1

@HerbiShtini grazie. Sono contento di sentire le mie risposte sono utili :) –