#node.js #typescript #oop #dependency-injection #sequelize.js
Вопрос:
Как я могу исправить эту ошибку ? Ниже приведены мои коды
IUserRepository и UserRepository:
import User from "./entity/User";
export default interface IUserRepository{
findAll():Promise<User[]>
}
import User from "./entity/User";
import IUserRepository from './IUserRepo';
export default class UserRepository implements IUserRepository{
public async findAll(): Promise<User[]>{
return await User.findAll()
}
}
Сервис IUserService и сервис пользователей:
import User from "./entity/User";
export default interface IUserRepository{
findAll():Promise<User[]>
}
import User from './entity/User';
import IUserService from './IUserService';
import IUserRepository from './IUserRepo';
export default class UserService implements IUserService{
public userRepo: IUserRepository
public constructor(userRepo:IUserRepository){
this.userRepo = userRepo
}
public async findAll(): Promise<User[]> {
return await this.userRepo.findAll()
}
}
Пользовательский контроллер:
import { Request, Response } from 'express';
import IUserService from './IUserService';
export default class UserController{
public userService:IUserService
public constructor(UserService:IUserService){
this.userService = UserService
}
public async findAll(req:Request, res:Response){
const allUser = await this.userService.findAll()
res.send(allUser)
}
}
сервер:
import express, { Application, Request, Response } from 'express'
import UserController from './UserController';
import UserService from './UserService';
import UserRepository from './UserRepository';
const app: Application = express()
const port = 3000
const userCont = new UserController(new UserService(new UserRepository()))
app.use(express.json());
app.get('/', userCont.findAll)
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})
ошибка:
(node:21576) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'userService' of undefined
at C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:11:36
at step (C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:33:23)
at Object.next (C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:14:53)
at C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:8:71
at new Promise (<anonymous>)
at __awaiter (C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:4:12)
at UserController.findAll (C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:44:16)
at Layer.handle [as handle_request] (C:UsershasanOneDriveMasaüstütype-ormnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsershasanOneDriveMasaüstütype-ormnode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (C:UsershasanOneDriveMasaüstütype-ormnode_modulesexpresslibrouterroute.js:112:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:21576) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:21576) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process
with a non-zero exit code.
(node:21576) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'userService' of undefined
at C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:11:36
at step (C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:33:23)
at Object.next (C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:14:53)
at C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:8:71
at new Promise (<anonymous>)
at __awaiter (C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:4:12)
at UserController.findAll (C:UsershasanOneDriveMasaüstütype-ormsrcUserController.ts:44:16)
at Layer.handle [as handle_request] (C:UsershasanOneDriveMasaüstütype-ormnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsershasanOneDriveMasaüstütype-ormnode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (C:UsershasanOneDriveMasaüstütype-ormnode_modulesexpresslibrouterroute.js:112:3)
(node:21576) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
У меня эта ошибка уже 4 дня, я сойду с ума из-за этой ошибки. Пожалуйста, помогите мне.
кстати, извините за мой плохой английский. если я буду писать меньше, я не смогу поделиться этим постом из-за сори за этот ххх спам
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Ответ №1:
Не могли бы вы опубликовать трассировку стека или ошибку? Я думаю, ты забыл это поставить.
Комментарии:
1. я добавил трассировку стека выше @yed2393
Ответ №2:
Вы не должны передавать функцию объекта, потому что вы теряете контекст
Вместо этого используйте функцию стрелки:
app.get('/', (req, res) => userCont.findAll(req,res))
Комментарии:
1. Спасибо, Айдер, ты спас мне жизнь 🙂 Я больше не злюсь