8

根据文档,我在控制器的构造函数中注入了一个服务,但结果是undefined.

processScraped.controller.ts

import { Controller, Post, Body } from '@nestjs/common';
import { ProcessScrapedService } from "./processScraped.service"

console.log(`\nController - ProcessScrapedService = `, ProcessScrapedService) // logs : class ProcessScrapedService { ......

@Controller('processScraped')
export class ProcessScrapedController {

    constructor(private readonly pss: ProcessScrapedService) {
        console.log(`constructor - pss = `, pss) // logs : undefined (Should not !)
        console.log(`constructor - this.pss = `, this.pss) // logs : undefined (Should not !)
    }

    @Post()
    async processScraped(@Body() body) {
        console.log(`processScraped - this.pss = `,this.pss) // logs : undefined (Should not !)
        return this.pss.processScraped(body) // TypeError: Cannot read property 'processScraped' of undefined
    }
}

所以 :

  • 服务存在

  • 导入后作为服务正确导入并记录

  • 当我将它注入我的控制器时,它是未定义的。

也许问题出在服务定义中?

processScraped.service.ts

import { Component } from '@nestjs/common';

@Component()
export class ProcessScrapedService {
    async processScraped(body) {
        // Some logic here
        return
    }
}

...或者也许在模块中?

processScraped.module.ts

import { Module } from '@nestjs/common';

import { ProcessScrapedController } from './processScraped.controller';
import { ProcessScrapedService } from './processScraped.service';

console.log(`\Module - nProcessScrapedService = `, ProcessScrapedService) // logs : class ProcessScrapedService { ......

@Module({
    controllers: [ProcessScrapedController],
    components: [ProcessScrapedService],
})
export class ProcessScrapedModule { }

我真的看不出我在这里做错了什么?

编辑- 这是我的依赖项:

"dependencies": {
    "@nestjs/common": "^4.5.9",
    "@nestjs/core": "^4.5.10",
    "@nestjs/microservices": "^4.5.8",
    "@nestjs/mongoose": "^3.0.1",
    "@nestjs/testing": "^4.5.5",
    "@nestjs/websockets": "^4.5.8",
    "@types/mongoose": "^5.0.9",
    "bluebird": "^3.5.1",
    "dotenv": "^5.0.1",
    "elasticsearch": "^14.2.2",
    "express": "^4.16.3",
    "mongoose": "^5.0.16",
    "mongoose-elasticsearch-xp": "^5.4.1",
    "reflect-metadata": "^0.1.12",
    "rxjs": "^5.5.6",
    "shortid": "^2.2.8"
  },
  "devDependencies": {
    "@types/node": "^8.0.0"
  }

和我的 tsconfig.json :

{
    "compilerOptions": {
        "target": "ES2017",
        "module": "commonjs",
        "lib": [ 
            "dom",
            "es2017"
        ],
        "outDir": "../../dist/server",
        "removeComments": true,
        "strict": true,
        "noImplicitAny": false,
        "typeRoots": [
            "node_modules/@types"
        ],
        "types": [
            "node"
        ],
        "experimentalDecorators": true
    }
}
4

2 回答 2

31

您的文件"emitDecoratorMetadata": true中缺少。tsconfig.json

于 2018-05-01T18:32:53.413 回答
15

刚刚在我的一个提供者中偶然发现了同样的问题 - 问题是我在将提供者@Injectable()添加到相应的模块后忘记用装饰器注释提供者。

于 2019-02-10T08:02:47.720 回答