我有两个类:
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), []);
}
购物车服务
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(CartService("SOME_NEW_KEY"))这是 typescript 中的无效语法,您可能会遇到类似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"))

关于javascript - 具有条件参数的javascript中的Singleton类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64981572/

10-13 21:30