在构造函数中声明的访问类属性

时间:2019-06-10 12:50:14

标签: typescript

我有以下课程:

export class CommandHandler {
  constructor(private readonly commands: Collection<string, BotCommand>) {}

  public static async load(loggingEnabled?: boolean): Promise<CommandHandler> {
    ...
    return new CommandHandler(commands);

我想访问另一个文件中的集合,在这里我调用该类并在我的索引中对其进行初始化,例如

(async () => {
  await createConnection();

  const client = new Client();

  client.once('ready', () => console.log(`${client.user.username} is online.`));

  const handler = await CommandHandler.load(true);

如何访问另一个文件中的集合?

import { CommandHandler } from '../../CommandHandler';

// I would like to access the collection here

1 个答案:

答案 0 :(得分:0)

您可以创建服务以在不同的类之间共享数据,以获取更多信息 read this

export class CommandHandlerService {
    //Properties which you want enabled from another classes
      someProperty;
   //

   public loadData(){
        // you can execute some method here

       // you can assign some values to the local properties
       this.someProperty = 'instance or new value';
   }
   // declare a get accessor for each property which want to get for example
   get property() {
       return this.someProperty;
   }
}

将其插入索引类中以获取init属性

constructor(
    private commandService: CommandHandlerService,
) {
    CommandHandlerService.loadData(); //load all service properties
}

将其注入要从命令服务中获取数据的类构造函数中。

     constructor(
    private commandService: CommandHandlerService,
) {
    let variable = CommandHandlerService.property //access to the service property
}

希望我能对您有所帮助。