我是 Typescript 和 InversifyJS 的新手。我想要实现的是跨多个文件共享变量值。我正在 main.ts 上的服务器启动时设置值,并尝试从 Controller 获取该值。我所做的是创建一个 @injectable 服务文件
服务.ts
import { injectable } from 'inversify';
@injectable()
export class SetGetService {
private _client : any;
get () : any {
return this._client;
}
set (client: any) {
this._client = client;
}
}
我可以从 main.ts 设置该值,但在其他文件上调用 SetGetService 后,该值未定义或为空。似乎它正在被重置或清除。
最佳答案
您可以在 main.ts
文件中执行以下操作:
const client = new Client();
container.bind<Client>("Client").toConstantValue(client);
然后在服务中:
import { injectable, inject } from 'inversify';
@injectable()
export class SetGetService {
@inject("Client") private _client: Client;
get () : any {
return this._client;
}
set (client: any) {
this._client = client;
}
}
如果客户端是数据库客户端并且其初始化是异步的,您可能需要使用以下内容:
// ioc_modules.ts
const asyncModule = new AsyncContainerModule(async (bind) => {
const client = await Client.getConnection();
bind<Client>("Client").toConstantValue(client);
});
// main.ts
(async () => {
await container.loadAsync(asyncModule);
})()
关于javascript - Typescript InversifyJS - 如何从 maint.ts 设置变量值并从 Controller 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49398155/