javascript中带条件参数的Singleton类

javascript中带条件参数的Singleton类,javascript,reactjs,typescript,oop,singleton,Javascript,Reactjs,Typescript,Oop,Singleton,我有两门课: 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 { re

我有两门课:

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__;
}
}
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), []);
}
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__;
  }
}
我想初始化CartService对象并像这样将其传递到userService中

useService(CartService(“一些新密钥”))

我尝试了很多方法,但都出现了错误。

userService(CartService(“SOME\u NEW\u KEY”)
typescript中的语法无效。您可能会遇到错误,例如,
类型“typeof CartService”的值不可调用。

在实例化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"))
试试这个:

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__;
}
}
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), []);
}
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()

此处未定义用户服务。您的意思是
useService
?是否要在不使用新关键字的情况下初始化?如果new关键字userService(new CartService(“SOME_new_KEY”)没有约束,请尝试or@RajaJaganathan是的,我想在没有新关键字的情况下初始化它。@gqstav是的,这是一个输入错误。其类型为“CartService”的useServiceArgument不能分配给类型为“{new():unknown;getInstance():unknown;}”的参数。类型“CartService”中缺少属性“getInstance”,但类型“{new():unknown;getInstance():unknown;}”中需要属性“getInstance”。获取此错误此处可再现的错误将很有帮助。注意,我在这里没有看到任何问题,你还缺了一节课。useService我必须在其中传递对象。像这样尝试