0

我是 Typescript 和 InversifyJS 的新手。我想要实现的是在多个文件之间共享变量值。我在 main.ts 上设置服务器启动时的值,并试图从控制器中获取该值。我所做的是创建了一个@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 之后,它是未定义的或为空的。它似乎正在被重置或清除。

4

1 回答 1

3

您可以在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);
})()
于 2018-03-21T16:07:40.277 回答