这里的答案是:“这取决于”。
如果提供者没有注入依赖项,那么从技术上讲,不,您不需要 @Injectable() 装饰器。装饰器在幕后所做的是强制 Typescript 发出构造函数参数元数据。 Nest 将在运行时读取该元数据以了解注入到提供程序中的内容。 This PR goes into more depth on the @Injectable() decorator itself
如果我们有以下课程
@Injectable()
export class Foo {
constructor(private readonly foo: string) {}
}
@Injectable()
export class Bar {
constructor(private readonly bar: string) {}
}
@Injectable()
export class FooBar {
constructor(private readonly foo: Foo, private readonly bar: Bar) {}
}
然后我们得到这样的编译输出
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
let Foo = class Foo {
constructor(foo) {
this.foo = foo;
}
};
Foo = __decorate([
Injectable(),
__metadata("design:paramtypes", [String])
], Foo);
export { Foo };
let Bar = class Bar {
constructor(bar) {
this.bar = bar;
}
};
Bar = __decorate([
Injectable(),
__metadata("design:paramtypes", [String])
], Bar);
export { Bar };
let FooBar = class FooBar {
constructor(foo, bar) {
this.foo = foo;
this.bar = bar;
}
};
FooBar = __decorate([
Injectable(),
__metadata("design:paramtypes", [Foo, Bar])
], FooBar);
export { FooBar };
__metadata('design:paramtypes', []) 是 Nest 最终读取的内容,并与 DI 容器注入令牌匹配