【问题标题】:angular 6 constructor overloading角度6构造函数重载
【发布时间】:2018-09-13 14:17:56
【问题描述】:

我是 typescript/angulat 的新手。我已经有一个获取 JsonP 的构造函数。我想为 HttpClientModule 创建一个新的构造函数。这是我当前的代码。

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

这是我试过的..

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

第一个 json api 停止工作。我想要与此等价的东西

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

【问题讨论】:

标签: angular typescript constructor overloading


【解决方案1】:

要在 Typescript 中执行此操作,它可能如下所示。基本上,您提供方法签名,然后是实现(必须处理所有各种签名)。

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

【讨论】:

    【解决方案2】:

    TypeScript 可以重载,请看这个问题: Constructor overload in TypeScript

    另一种常见的做法是为可以包含选项的函数提供可选参数。比如:

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

    【讨论】:

    • 这个答案已经过时了,因为 TypeScript 绝对支持构造函数重载。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多