eggjs / egg

🥚 Born to build better enterprise frameworks and apps with Node.js & Koa

Home Page:https://eggjs.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

eggv3版本使用HTTPController创建的controller要怎么获取到app对象?

2559490343 opened this issue · comments

在此输入你需要反馈的 Bug 具体信息(Bug in Detail):

我是eggjs小白,想问一下大佬,我按照官方文档使用npm init egg --type=ts命令创建的ts项目,在controller里面无法获取到app对象,此controller是使用了HTTPController注解创建的,也试过继承Controller类来获取app对象,但是启动后会报错“Cannot read properties of undefined (reading 'app')”,想请教一下如何在使用注解创建的controller内获取app对象

可复现问题的仓库地址(Reproduction Repo)

eggjs.zip

Node 版本号:

16.16.0

Eggjs 版本号:

3.17.3

相关插件名称与版本号(PlugIn and Name):

egg-mysql@4.0.0

操作平台与版本号(Platform and Version):

Windows 11 专业工作站版(22H2)

commented

请问解决了吗?
我也遇到同样的问题

commented

参考这个文档:https://github.com/eggjs/tegg
这种方式不能直接使用 ctx 和 app,但是可以用他们底下的模块。用是什么注什么。

import { EggLogger, EggAppConfig } from 'egg';
import { Inject } from '@eggjs/tegg';

@ContextProto()
export class HelloService {
  // 在 config.default.js 中
  // 配置了 customLogger,
  // 名称为 bizLogger
  @Inject({ name: 'bizLogger' })
  logger: EggLogger;

  @Inject()
  config: EggAppConfig;

  async hello(user: User): Promise<string> {
    this.logger.info(`[HelloService] hello ${user.name}`);
    const echoResponse = await this.echoAdapter.echo({ name: user.name });
    return `hello, ${echoResponse.name}`;
  }
}
commented

参考这个文档:https://github.com/eggjs/tegg 这种方式不能直接使用 ctx 和 app,但是可以用他们底下的模块。用是什么注什么。

import { EggLogger, EggAppConfig } from 'egg';
import { Inject } from '@eggjs/tegg';

@ContextProto()
export class HelloService {
  // 在 config.default.js 中
  // 配置了 customLogger,
  // 名称为 bizLogger
  @Inject({ name: 'bizLogger' })
  logger: EggLogger;

  @Inject()
  config: EggAppConfig;

  async hello(user: User): Promise<string> {
    this.logger.info(`[HelloService] hello ${user.name}`);
    const echoResponse = await this.echoAdapter.echo({ name: user.name });
    return `hello, ${echoResponse.name}`;
  }
}

这是正确的方式。注入需要的对象。

commented

文档是不是得补充一下相关的内容了?