eggjs / egg

🥚 Born to build better enterprise frameworks and apps with Node.js & Koa
https://eggjs.org
MIT License
18.88k stars 1.81k forks source link

在 service 中 extends egg 暴露的 Service 项目无法启动 #5322

Closed mqliutie closed 4 months ago

mqliutie commented 4 months ago

Your detail info about the Bug:

自己的service 如果不继承 Service就无法拿到 this.app 但是继承项目无法启动

import { EggLogger, Service } from 'egg';
import { SingletonProto, AccessLevel, Inject } from '@eggjs/tegg';

@SingletonProto({
  // 如果需要在上层使用,需要把 accessLevel 显示声明为 public
  accessLevel: AccessLevel.PUBLIC,
})
export class ArticlesService extends Service{
  // 注入一个 logger
  @Inject()
  logger: EggLogger;

  // 封装业务
  async hello(userId: string): Promise<string> {
    const result = { userId, handledBy: 'foo module' };
    this.logger.info('[hello] get result: %j', result);
    return `hello, ${result.userId}`;
  }
}

报错信息如下:

2024-06-03 12:02:26,093 ERROR 41276 [-/127.0.0.1/97622daa-408a-47f5-8ad7-439dcd91e244/1ms GET /] nodejs.TypeError: Cannot read properties of undefined (reading 'app')
    at new BaseContextClass (/Users/123/study/egg-example/node_modules/egg-core/lib/utils/base_context_class.js:25:20)
    at new BaseContextClass (/Users/123/study/egg-example/node_modules/egg/lib/core/base_context_class.js:13:1)
    at new ArticlesService (/Users/123/study/egg-example/app/module/records/service/ArticlesService.ts:8:8)

Reproduction Repo

本地环境通过 npm init egg --type=ts 初始化的

Node Version

v20.14.0

Eggjs Version

^3.15.0

Plugin Name and its version

没用插件

Platform and its version

macOS 12.7.5

mqliutie commented 4 months ago

通过 @Inject 可以注入 context, 官方文档没有, 查阅了 https://github.com/eggjs/tegg#readme