jak*_*oci 11 javascript dependency-injection nestjs
是否可以仅使用 Nest.js 框架中的 DI 和 IoC 功能?如果是的话,如何实现?
我尝试以这种方式实现它:
import { NestFactory } from "@nestjs/core";
import { Module, Injectable } from "@nestjs/common";
@Injectable()
class AppRepository {
sayHi() {
console.log("app repository");
console.log("Hello");
}
}
@Injectable()
class AppService {
constructor(private appRepository: AppRepository) {}
sayHi() {
console.log("app service");
this.appRepository.sayHi();
}
}
@Module({
imports: [],
providers: [AppService, AppRepository]
})
class AppModule {
constructor(private appService: AppService) {}
sayHi() {
console.log("app module");
this.appService.sayHi();
}
}
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);
const module = app.get<AppModule>(AppModule);
module.sayHi();
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
但是当我运行代码时我得到:
app module
(node:70976) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'sayHi' of undefined
at AppModule.sayHi (/Users/jakub/projects/nest-di-clean/build/main.js:47:25)
at /Users/jakub/projects/nest-di-clean/build/main.js:60:16
at Generator.next (<anonymous>)
at fulfilled (/Users/jakub/projects/nest-di-clean/build/main.js:11:58)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
Run Code Online (Sandbox Code Playgroud)
所以我得到了 的实例,但没有注入 的AppModule实例。AppService
我想在我正在贡献的库中使用它,它不需要控制器和其他服务器端的东西。
我找到了解决方案。我没有创建一个新项目,nest-cli只是使用 TypeScript 创建了一个空的 npm 项目,并添加了@nestjs/common和@nestjs/core作为依赖项(我想最小化依赖项)。我的错误是在tsconfig.json我忘记允许的文件中emitDecoratorMetadata。这是我的package.json文件tsconfig.json,供感兴趣的人使用:
package.json
{
"name": "nest-di-clean",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"compile": "yarn tsc",
"start": "node ./build/main.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"@nestjs/common": "^6.11.5",
"@nestjs/core": "^6.11.5",
"reflect-metadata": "^0.1.13",
"rxjs": "^6.5.4"
},
"devDependencies": {
"@types/node": "^13.7.0",
"typescript": "^3.7.5"
}
}
Run Code Online (Sandbox Code Playgroud)
tsconfig.json
{
"compilerOptions": {
"target": "ES2015",
"module": "commonjs",
"outDir": "./build",
"strict": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true
}
}
Run Code Online (Sandbox Code Playgroud)
文件的内容main.js全部在我的问题中。