Comments (12)
Hi @alexcorvi @thomrick,
Let's add:
"emitDecoratorMetadata": true,
to your tsconfig.json
file. It is my mistake - I didn't mention about it in the documentation.
EDIT: I answered using my old account.
from nest.
Hi @alexcorvi,
Can you paste your code here? With Typescript, Nest should deduce dependency just by type.
from nest.
Hi all,
For my use case I had to use @Inject() parameter decorator instead of @Dependencies():
import {Controller, Inject, RequestMapping, RequestMethod} from 'nest.js';
import {UserService} from './user.service';
@Controller({ path: 'users'})
export class UserController {
constructor(@Inject(UserService) private userService) {}
@RequestMapping()
public async getAllUsers(request, response) {
const users = await this.userService.getAllUsers();
response.status(200).json(users);
}
@RequestMapping({ path: '/:id' })
public async getUser(request, response) {
const user = await this.userService.getUser(request.params.id);
response.status(200).json(user);
}
@RequestMapping({ method: RequestMethod.POST })
public async addUser(request, response) {
const message = await this.userService.addUser(request.body.user);
response.status(201).json(message);
}
}
I use the 1.0.0-rc8
from nest.
Hi @thomrick,
Let's try:
constructor(private userService: UserService) {}
With Typescript, it should works. If not - it is an issue.
from nest.
Controller
import {Dependencies,RequestMethod,Controller,RequestMapping} from 'nest.js';
import {Request,Response,NextFunction} from "@types/express"
import {UsersService} from "./users.service";
import {UserRequest} from "./user.typing";
@Controller({path: 'users'})
export class UsersController {
constructor(private usersService: UsersService) {
console.log(usersService,this.usersService);
}
@RequestMapping()
async getAllUsers(req:UserRequest, res:Response) {
const users = await this.usersService.getAllUsers();
res.status(200).json(users);
}
@RequestMapping({ path: '/:id' })
async getUser(req:UserRequest, res:Response) {
console.log(req.params.id);
const user = await this.usersService.getUser(req.params.id);
res.status(200).json(user);
}
@RequestMapping({ method: RequestMethod.POST })
async addUser(req:UserRequest, res:Response) {
const msg = await this.usersService.getUser(req.body.user);
res.status(201).json(msg);
}
}
Service
Component()
export class UsersService {
private users = [
{ id: 1, name: "John Doe" },
{ id: 2, name: "Alex Corvi" },
{ id: 3, name: "Who Knows" },
];
async getAllUsers():Promise<User[]> {
return await this.users;
}
async getUser(id: string):Promise<User> {
const user = this.users.find((user) => user.id.toString() === id);
if (!user) throw new HttpException("User not found", 404);
return await user;
}
async addUser(user:User):Promise<UserAdded> {
this.users.push(user);
return await {
id:user.id,
name:user.name,
date:new Date().getTime()
};
}
}
Module
import {Module} from 'nest.js';
import {UsersController} from './users.controller';
import {UsersService} from './users.service';
@Module({
controllers: [ UsersController ],
components: [ UsersService ],
})
export class UsersModule {}
Result
Now when running ts-node src/server.ts
Here's the output:
[Nest] 712 - 4/12/2017, 10:43:56 PM [NestFactory] Starting Nest application...
[Nest] 712 - 4/12/2017, 10:43:56 PM [InstanceLoader] ApplicationModule dependencies initialized
undefined undefined
[Nest] 712 - 4/12/2017, 10:43:56 PM [InstanceLoader] UsersModule dependencies initialized
[Nest] 712 - 4/12/2017, 10:43:56 PM [RoutesResolver] UsersController:
[Nest] 712 - 4/12/2017, 10:43:56 PM [RouterBuilder] Mapped {/, GET} route
[Nest] 712 - 4/12/2017, 10:43:56 PM [RouterBuilder] Mapped {/:id, GET} route
[Nest] 712 - 4/12/2017, 10:43:56 PM [RouterBuilder] Mapped {/, POST} route
[Nest] 712 - 4/12/2017, 10:43:56 PM [NestApplication] Nest application is ready!
Navigating to localhost:3000/users
gives the following error in the console:
[Nest] 712 - 4/12/2017, 10:52:53 PM [ExceptionsHandler] Cannot read property 'getAllUsers' of undefined
TypeError: Cannot read property 'getAllUsers' of undefined
from nest.
@alexcorvi - please, show your tsconfig.json
file.
from nest.
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"sourceMap": false,
"strictNullChecks": true,
"experimentalDecorators": true,
"outDir": "./dist/"
},
"exclude": ["node_modules"],
"files": ["./src/server.ts"]
}
from nest.
Here's a full repo: https://github.com/alexcorvi/typescript-dependency-management-issue
from nest.
Hey @kamilmysliwiec,
Sorry it doesn't work without the @Inject() decorator :-/
I try to log what happened in the UserController constructor:
Without @Inject() decorator:
[Nest] 3931 - 2017-04-13 08:52:16 [NestFactory] Starting Nest application...
- - - - UserController constructor - - - -
undefined
- - - - UserController constructor - - - -
[Nest] 3931 - 2017-04-13 08:52:16 [InstanceLoader] ApplicationModule dependencies initialized
[Nest] 3931 - 2017-04-13 08:52:16 [RoutesResolver] UserController:
[Nest] 3931 - 2017-04-13 08:52:16 [RouterBuilder] Mapped {/, GET} route
[Nest] 3931 - 2017-04-13 08:52:16 [RouterBuilder] Mapped {/:id, GET} route
[Nest] 3931 - 2017-04-13 08:52:16 [RouterBuilder] Mapped {/, POST} route
[Nest] 3931 - 2017-04-13 08:52:16 [NestApplication] Nest application is ready!
Application is listening at port 8080
With the @Inject() decorator:
[Nest] 3937 - 2017-04-13 08:52:42 [NestFactory] Starting Nest application...
- - - - UserController constructor - - - -
UserService {
users:
[ { id: '1', name: 'John Doe' },
{ id: '2', name: 'Alice Cairo' },
{ id: '3', name: 'Who Knows' } ] }
- - - - UserController constructor - - - -
[Nest] 3937 - 2017-04-13 08:52:42 [InstanceLoader] ApplicationModule dependencies initialized
[Nest] 3937 - 2017-04-13 08:52:42 [RoutesResolver] UserController:
[Nest] 3937 - 2017-04-13 08:52:42 [RouterBuilder] Mapped {/, GET} route
[Nest] 3937 - 2017-04-13 08:52:42 [RouterBuilder] Mapped {/:id, GET} route
[Nest] 3937 - 2017-04-13 08:52:42 [RouterBuilder] Mapped {/, POST} route
[Nest] 3937 - 2017-04-13 08:52:42 [NestApplication] Nest application is ready!
from nest.
Hey @smsites,
You find the right solution to the issue with the "emitDecoratorMetadata": true
Let's see my tsconfig.json :
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"outDir": "dist",
"typeRoots": [
"node_modules/@types"
]
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}
And the UserController class code:
import {Controller, RequestMapping, RequestMethod} from 'nest.js';
import {UserService} from './user.service';
@Controller({ path: 'users'})
export class UserController {
constructor(private userService: UserService) {
console.log('- - - - UserController constructor - - - -');
console.log('UserService : ', this.userService);
console.log('- - - - UserController constructor - - - -');
}
@RequestMapping()
public getAllUsers(request, response) {
this.userService.getAllUsers()
.then(users => {
response.status(200).json(users);
});
}
@RequestMapping({ path: '/:id' })
public getUser(request, response) {
this.userService.getUser(request.params.id)
.then(user => {
response.status(200).json(user);
});
}
@RequestMapping({ method: RequestMethod.POST })
public addUser(request, response) {
this.userService.addUser(request.body.user)
.then(message => {
response.status(201).json(message);
});
}
}
No need the @Inject() param decorator.
from nest.
@kamilmysliwiec Confirmed, this solved it for me.
from nest.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
from nest.
Related Issues (20)
- I have a question about dependency injection and module import HOT 1
- Supply time to TypeOrmLogger.logQuery() HOT 1
- TCP.onStreamRead (node:internal/stream_base_commons:217:20) HOT 1
- RabbitMQ Bug Microservices HOT 1
- nx 18 + nest + webpack + serverless breaking with error src/main.handler is undefined or not exported HOT 1
- NestJS doesn't handle "Operation failed: QueueDeclare" error from amqplib HOT 1
- Problems Encountered with NestJS and pnpm in a Monorepo Setup HOT 1
- grpc microservice stops listening to requests after version 10.3.3 (needs peer dependency) HOT 1
- perf: caching return value for some functions HOT 1
- The request body does not return an object whose value is an array of objects
- Jest spy doesn't work on Microservices Controller (EventPattern) E2E Tests
- Feature Request: Support for Bun.js HOT 1
- Multi-tenant app fail on first non durable tree request HOT 2
- Kafka Microservice Error When Consumer Has Not Joined the Consumer Group
- LoggerService transforms the instance of Error when controller throws an Error HOT 3
- Easy way to compose ORed validators HOT 1
- Not sure if it is bug or feature request, nest middleware in jest runs before any other express middleware HOT 2
- Devtools with microservices: Error: listen EADDRINUSE: address already in use :::8000 HOT 4
- Hooks in global module which imported more than twice might called multiple times HOT 2
- Overide providers from imported module (not in testing context)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from nest.