首页 > 解决方案 > 如何在其构造函数中使用 vars 创建单例?

问题描述

我的角度项目中有这个单身人士:

class CustomersServicesHandler
{
    private static _instance: CustomersServicesHandler;

    bridalEventId: string = null;

    private constructor(private _customerService: CustomersService,
        private _globalFunctionsService: GlobalFunctionsService)
    {
        //...
    }

    public static get Instance()
    {
        return this._instance || (this._instance = new this());//this is my problem
    }
}

如您所见,我在构造函数中使用了一些服务。问题从我创建时开始new this()- 我需要传递也获取变量的变量(服务)。

标签: angulartypescriptoop

解决方案


尝试CustomersServicesHandler在要使用它的类中注入:

class ClassYouWantToUseItIn {
    constructor(private customersServicesHandler: CustomersServicesHandler) {
    }
}

CustomersServiceAngular 会为你处理和的创建/传递GlobalFunctionsService


推荐阅读