Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 392
Vũ Anh Dũng Avatar asked Dec 02 '25 05:12

Vũ Anh Dũng


1 Answers

@Injectable() is how you tell Nest this is a class that can have dependencies that should be instantiated by Nest and its DI system. The code you posted works because there are no injected dependencies. If, instead, you had

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

export class UserService {
  constructor(private readonly otherService: OtherService) {}
  getUser() {
    return userMock
  }
}

OtherService would come back undefined due to UserService not being @Injectable()

like image 124
Jay McDoniel Avatar answered Dec 03 '25 23:12

Jay McDoniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!