作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了一个奇怪的问题,Container.get(MyServiceName);返回所需的服务,但未定义用 @Inject() 装饰的类属性。
我试过用@Service() 装饰类
我确实在我的应用程序的入口点导入了 reflect-metada导入“反射(reflect)元数据”;
我想知道这是否与事实有关,即我不是直接从我的 node_modules 而是从我的依赖项使用 typedi?
应用程序既不使用 Express 框架也不使用路由 Controller
我的 tsconfig.json:
"compilerOptions": {
"declaration": true,
"pretty": true,
"esModuleInterop": true,
"target": "esnext",
"noImplicitAny": true,
"noImplicitReturns": true,
"noUnusedLocals": false,
"moduleResolution": "node",
"noUnusedParameters": true,
"strictPropertyInitialization": false,
"module": "commonjs",
"lib": ["dom", "es2018"],
"importHelpers": true,
"outDir": "./dist",
"strict": true,
"typeRoots": ["node_modules/@types"],
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"sourceMap": true
},
"include": ["./src/**/*"],
"exclude": ["node_modules", "./dist/**/*"]
}
我要注入(inject)的服务
import MyServiceName from '../services/MyServiceName';
import { Container, Inject, Service } from 'my_dependency/lib';
export default class SomeClass{
@Inject()
private readonly someService: MyServiceName;
public async someMethod(): SomeResponseType {
const thatWorks = Container.get<MyServiceName>(MyServiceName);
console.log(this.someService); // undefined
console.log(thatWorks); // proper class
}
}
我要注入(inject)的服务
@Service()
export default class MyServiceName {
public async someMethod(): SomeReturnType {
return someReturnedData;
}
}
我想通过@Inject() 装饰器注入(inject)我的依赖
最佳答案
您需要使用 Container#get
创建您的 SomeClass
实例,否则容器将无法注入(inject)该属性。
这对我有用:
// a.ts
import { Service } from "typedi";
@Service()
export class Foo {
foo() {
return 10;
}
}
// b.ts
import { Foo } from "./a";
import { Inject } from "typedi";
export class Bar {
@Inject() private readonly service: Foo
foo() {
console.log(this.service);
}
}
// test.ts
import "reflect-metadata";
import { Bar } from "./b";
import { Container } from "typedi";
const noFoo = new Bar();
noFoo.foo(); // yields undefined
const withFoo = Container.get<Bar>(Bar);
withFoo.foo(); // yields Foo
关于node.js - TypeDI @Inject() 不起作用,但 Container.get() 起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55684776/
我遇到了一个奇怪的问题,Container.get(MyServiceName);返回所需的服务,但未定义用 @Inject() 装饰的类属性。 我试过用@Service() 装饰类 我确实在我的应用
我想在我的 UserService 中注入(inject)存储库。 但我不知道该怎么做。 我正在使用 typescript、typedi 和 sequelize。 我认为,服务的加载速度比加载器快。
我是一名优秀的程序员,十分优秀!