【问题标题】:Singleton class in javascript with conditional parameter带有条件参数的javascript中的单例类
【发布时间】:2020-11-24 06:56:57
【问题描述】:

我有两门课:

useService.ts

import { useMemo } from 'react';

/**
 * Hook will take the singletone service instance later keeping it memoized
 * @param service
 */
export function useService<T> ( service: { new (): T; getInstance (): T } ): T {
    return useMemo<T>(() => service.getInstance(), []);
}

/**
 * Hook will take instance of the given class memoized
 * @param Class
 * @param args
 */
export function useClass<S, A extends []> ( Class: { new ( ...args: A ): S }, ...args: A ): S {
    return useMemo<S>(() => new Class(...args), []);
}

CartService.ts

var CART_ITEMS_KEY = 'SOME_KEY';

export class CartService {
private static __SELF__: CartService;
private __items: CartItem[] = [];
private auth: AuthService;
private api: APIService;
private endpoint: AxiosInstance;

constructor (cartItemsKey) {
    CART_ITEMS_KEY = cartItemsKey;
    this.auth = AuthService.getInstance();
    this.api = APIService.getInstance();
    this.endpoint = this.api.createEndpoint('cart');

    this.init();
}

/**
 * Get singletone service instance
 */
public static getInstance (): CartService {
    if ( !CartService.__SELF__ ) {
        CartService.__SELF__ = new CartService();
    }

    return CartService.__SELF__;
}
}

我想初始化一个 CartService 对象并像这样在 userService 中传递它。

useService(CartService("SOME_NEW_KEY"))

我尝试了很多方法,但都遇到了错误。

【问题讨论】:

  • userService 此处未定义。你的意思是useService
  • 您想在没有新关键字的情况下进行初始化吗?如果没有新关键字 userService(new CartService("SOME_NEW_KEY")) 或的约束,请尝试
  • @RajaJaganathan 是的,我想在没有新关键字的情况下启动它。
  • @gqstav 是的,这是一个错字。它的使用服务

标签: javascript reactjs typescript oop singleton


【解决方案1】:

userService(CartService("SOME_NEW_KEY"))打字稿中的语法无效,您可能会收到类似Value of type 'typeof CartService' is not callable.的错误

在实例化 CartService 时,我们需要将 cartItemsKey 传递给构造函数。

  /**
   * Get singleton service instance
   */
  public static getInstance(cartItemsKey): CartService {
    if (!CartService.__SELF__) {
      CartService.__SELF__ = new CartService(cartItemsKey);
    }

    return CartService.__SELF__;
  }

如下调用

userService(CartService.getInstance("SOME_NEW_KEY"))

【讨论】:

【解决方案2】:

试试这个:

useService.ts

import { useMemo } from 'react';

/**
 * Hook will take the singleton service instance later keeping it memoized
 * @param service
 */
export function useService<T>(
  service: {
    new (): T;
    getInstance(...args: String[]): T;
  },
  args: String[]
): T {
  return useMemo<T>(() => service.getInstance(...args), []);
}

/**
 * Hook will take instance of the given class memoized
 * @param Class
 * @param args
 */
export function useClass<S, A extends []>(
  Class: { new (...args: A): S },
  ...args: A
): S {
  return useMemo<S>(() => new Class(...args), []);
}

CartService.ts

export class CartService {
  private static __SELF__: CartService;
  private cartItemsKey: String;
  private cartId: String;

  constructor(cartItemsKey: String = 'default', cartId: String = 'default') {
    this.cartItemsKey = cartItemsKey;
    this.cartId = cartId;
  }

  log() {
    console.log('cartId: ' + this.cartId);
    console.log('cartItemsKey: ' + this.cartItemsKey);
  }

  /**
   * Get singletone service instance
   */
  public static getInstance(...args: String[]): CartService {
    if (!CartService.__SELF__) {
      CartService.__SELF__ = new CartService(...args);
    }

    return CartService.__SELF__;
  }
}

然后像这样使用它:

let cartService = useService(CartService, [
    'SOME_KEY_FROM_TEST',
    'SOME_ID_FROM_TEST'
  ]);
cartService.log()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2011-05-11
    • 2012-10-08
    • 2015-06-15
    • 2019-02-28
    • 2017-03-16
    相关资源
    最近更新 更多