NestJS 中的可注入是什么?

Vũ *_*ũng 14 node.js typescript nestjs

我正在学习 NestJS,这是我的简单服务:

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

const userMock = [{ account: 'dung', password: '12345678' }];

@Injectable()
export class UserService {
  getUser() {
    return userMock
  }
}

Run Code Online (Sandbox Code Playgroud)

我不太了解@InjectableNestJS。一些教程告诉@Injectable我们@Controller知道这是一个安装并且可以将其用作依赖项注入。但当我删除它时,它仍然有效。

请举例说明有@Injectable和没有的区别@Injectable

Jay*_*iel 28

@Injectable()就是告诉 Nest 这是一个可以具有依赖项的类,这些依赖项应该由 Nest 及其 DI 系统实例化。您发布的代码可以工作,因为没有注入依赖项。相反,如果你有

const userMock = [{ account: 'dung', password: '12345678' }];

export class UserService {
  constructor(private readonly otherService: OtherService) {}
  getUser() {
    return userMock
  }
}
Run Code Online (Sandbox Code Playgroud)

OtherServiceundefined会因为UserService不存在而回来@Injectable()


nin*_*0hy 9

@Injectable()注释允许您注入实例。

当然,该实例应该有一个 @Injectible() 注释。

让我给你举个例子。

@Injectable()
export class PersonService {
  getName() {
    return 'ninezero90hy';
  }
}
Run Code Online (Sandbox Code Playgroud)
@Injectable()
export class AppService {
  constructor(private readonly personService: PersonService) {
    Logger.log(this.personService.getName())
  }
}
Run Code Online (Sandbox Code Playgroud)

打印“ninezero90hy”

--

如果没有AppService或PersonService@Injectible()注解,则会出现错误。

--

使用@Injectible()注释

您可以定义注射范围。

这意味着nestjs容器创建了一个实例。

--

参考:

export declare enum Scope {
    /**
     * The provider can be shared across multiple classes. The provider lifetime
     * is strictly tied to the application lifecycle. Once the application has
     * bootstrapped, all providers have been instantiated.
     */
    DEFAULT = 0,
    /**
     * A new private instance of the provider is instantiated for every use
     */
    TRANSIENT = 1,
    /**
     * A new instance is instantiated for each request processing pipeline
     */
    REQUEST = 2
}

Run Code Online (Sandbox Code Playgroud)

如果不使用@Injectible()注解,nestjs不会管理实例,所以DI过程中会出现错误。

在此输入图像描述