Sye*_*zmi 5 javascript oop singleton typescript reactjs
我有两个班级:
使用Service.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), []);
}
Run Code Online (Sandbox Code Playgroud)
购物车服务.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__;
}
}
Run Code Online (Sandbox Code Playgroud)
我想初始化一个 CartService 对象并像这样在 userService 中传递它。
使用服务(购物车服务(“SOME_NEW_KEY”))
我尝试了很多方法,但都出现错误。
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__;
}
Run Code Online (Sandbox Code Playgroud)
像下面这样调用
userService(CartService.getInstance("SOME_NEW_KEY"))
Run Code Online (Sandbox Code Playgroud)