0

I am new to typescript/angulat. I already have a constructor fetching JsonP. I want to create a new constructor for HttpClientModule. This is my current code.

export class DataService {
    constructor(private _jsonp: Jsonp) {
        this.apikey = 'xxx';
    }
}

This is what I tried..

export class DataService {
    constructor(private _jsonp: Jsonp, private http: HttpClient) {
        this.apikey = 'xxx';
    }
}

The first json api stops working. I want something equivalent to this

export class DataService {
    constructor(private _jsonp: Jsonp) {
        this.apikey = 'xxx';
    }
    constructor(http: HttpClient) {}
}
Milo
  • 3,365
  • 9
  • 30
  • 44
  • Possible duplicate of [Constructor overload in TypeScript](https://stackoverflow.com/questions/12702548/constructor-overload-in-typescript) – Edodso2 Dec 05 '18 at 20:34

2 Answers2

0

To do this in Typescript it could look something like the following. Basically, you provide the method signatures and then the implementation (which has to handle all of the various signatures).

export class DataService {
    constructor(private _jsonp: Jsonp);
    constructor(http: HttpClient);

    // Implementation of the constructor
    constructor(api: Jsonp | HttpClient){
        // some sort of test to tell what type the parameter is
        if (/* api is Jsonp */) {
            // is Jsonp, not HttpClient
            this.apikey = 'xxx';
        }
    }
}
LocalPCGuy
  • 6,006
  • 2
  • 32
  • 28
-1

Overloading is possible in TypeScript, please see this question: Constructor overload in TypeScript

Another common practice is to provide an optional parameter to functions that can contain options. Something like:

export class DataService {
  constructor(private _jsonp: Jsonp, private http: HttpClient) {
    this.apikey = 'xxx';
  }

  get(params?, options?) {
    if (this.options && this.options.service === 'jsonp') {
     // use the _jsonp service
    } else {
     // user the http service
    }
  }
}
Edodso2
  • 122
  • 1
  • 6