我尝试创建一个单例服务类,在其中实例化一个连接到后端的connection对象,以便在每个组件中重用connection对象,所以我已经做到了:
const {
Kuzzle,
WebSocket
} = require('kuzzle-sdk');
class KuzzleService {
static instance = null;
static async createInstance() {
var object = new KuzzleService();
object.kuzzle = new Kuzzle(
new WebSocket('localhost'),{defaultIndex: 'index'}
);
await object.kuzzle.connect();
const credentials = { username: 'user', password: 'pass' };
const jwt = await object.kuzzle.auth.login('local', credentials);
return object;
}
static async getInstance () {
if (!KuzzleService.instance) {
KuzzleService.instance = await KuzzleService.createInstance();
}
return KuzzleService.instance;
}
}
const kuzzleService = KuzzleService.getInstance();
export default kuzzleService;但是当我在组件中导入服务时,如下所示:
import kuzzleService from "../services/kuzzle-service.js";然后我打印出来:
async componentDidMount(){
console.log(JSON.stringify(kuzzleService.kuzzle));
}它给了我“未定义的”。我应该以另一种方式导入服务吗?
发布于 2019-04-11 16:12:12
这可能是因为在导出kuzzleService时,.getInstance()给出的承诺还没有得到解决。
您应该导出.getInstance函数并在componentDidMount中等待它,如下所示:
export default KuzzleService; // export the singleton directlyasync componentDidMount(){
const kuzzle = await KuzzleService.getInstance();
console.log(kuzzle);
}https://stackoverflow.com/questions/55621314
复制相似问题