Search code examples
node.jstypescriptnestjs

What is Injectable in NestJS?


I am studying NestJS, here is my simple service:

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

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

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

I not really understand @Injectable in NestJS. Some tutorial tell @Injectable tell the @Controller know it's an install and can use it as a Dependency Injection. But when I remove it, it's still working.

Please give an example about difference between @Injectable and without @Injectable


Solution

  • @Injectable() annotation allows you to inject instances.

    Of course, that instance should have an @Injectible() annotation.

    Let me show you an example.

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

    print 'ninezero90hy'

    --

    If there is no AppService or PersonService @Injectible() annotation, an error occurs.

    --

    Using the @Injectible() annotation

    You can define the injection range.

    This means that the nestjs container creates an instance.

    --

    Reference:

    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
    }
    
    

    If you don't use @Injectible() annotations, nestjs doesn't manage instances, so an error will occur in the DI process.