How to extend a class in TypeScript?

Serhiy picture Serhiy · Jun 20, 2016 · Viewed 25.3k times · Source

I have few services ,which have the same code inside:

 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;
    };
}

I wanted to move the code to separate file http_base_clas.ts and to reuse code as much as possible.Here is 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;
        };
    }
}

How to extend http_base_class into 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;
        });
    }
}

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jun 20, 2016
class AuthenticationService extends HttpBaseClass {
  constructor(http:Http) {
    super(http);
  }

  private authRequest (url) {
    ...
  }
}