0
请你能帮我解决我的路由问题吗?我试图在Node.js(express)中使用typescript和存储库模式来创建REST API。快速 - REST API - 存储库实例在路由期间丢失
我有两个泛型类BaseRepository和BaseController一起处理基本的CRUD交易。其他域控制器是从这些派生出来的。
有我的代码:
productRouter.ts用来处理路线:
import { Router } from 'express';
import { ProductController } from '../controllers/ProductController';
class ProductRouter {
private _router: Router;
private _controller: ProductController;
constructor() {
this._router = Router();
this._controller = new ProductController;
}
get routes(): Router {
this._router.get('/product', this._controller.getAll);
this._router.post('/product', this._controller.create);
this._router.get('/product/:id', this._controller.getById);
this._router.put('/product/:id', this._controller.update);
this._router.delete('/product/:id', this._controller.delete);
return this._router;
}
}
productController.ts用于初始化的BaseRepository其从BaseController的。
import { BaseController } from '../common/BaseController';
import { BaseRepository, IRepository } from '../common/BaseRepository';
import { Product, IProduct } from '../models/Product';
export class ProductController extends BaseController<IProduct> {
constructor() {
const productRepository = new BaseRepository<IProduct>(Product);
super(productRepository);
}
}
BaseController.ts
export class BaseController<T> implements IController {
private _repository: IRepository<T>;
constructor(repository: IRepository<T>) {
this._repository = repository;
}
getAll(req: Request, res: Response, next: NextFunction): void {
this._repository.getAll((err, result) => {
if (err)
res.send(err);
res.json(result);
});
}
我每次导航到合适的路径,我得到以下错误:
TypeError: Cannot read property '_repository' of undefined
at BaseController.getAll (C:\Users\vrbat\Documents\Projects\router-test\src\api\common\BaseController.ts:19:13)
enter code here
我不知道为什么,因为_repository属性是在productController.ts中进行的。
哪一行是你的BaseController.ts中的第19行。根据错误消息,我们需要看到第19行。 – Eray
第19行是调用this._repository.getAll函数的地方。 – jezikk