构造函数中带有DI的新对象实例

时间:2019-04-06 17:35:59

标签: angular ionic-framework ionic4

我是Inonic / Angular的新手。

我的问题是,我已经创建了一个使用DI的类:

import { HttpServiceProvider } from './../providers/http-service/http-service';

export class HttpWrapper{

    private _url: string;
    private _port: number;
    private _api: string;
    private _headers: Map<string, string>;

    constructor(private httpServie: HttpServiceProvider, url: string, port: number, api: string){
        this.url = url;
        this.port = port;
        this.api = api;
    }

当我要创建此类的新实例时,需要向构造函数提供“ HttpServiceProvider”。启动此类新对象的正确方法是什么? (不提供“ HttpServiceProvider”)。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用parameter初始化类的null,然后在初始化新的error时不会给您Object

示例:

export class HttpWrapper {

    private _url: string;
    private _port: number;
    private _api: string;
    private _headers: Map<string, string>;

    constructor(private httpServie: HttpServiceProvider = null, url: string, port: number, api: string){
        this.url = url;
        this.port = port;
        this.api = api;
    }

更新:

您还可以像这样将参数设置为可选:

export class HttpWrapper {

    private _url: string;
    private _port: number;
    private _api: string;
    private _headers: Map<string, string>;

    constructor(url: string, port: number, api: string, private httpServie?: HttpServiceProvider){
        this.url = url;
        this.port = port;
        this.api = api;
    }

以下是示例:Link