【发布时间】: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