请您解决我的路由问题吗?我正在尝试使用node.js(express(中的Typescript和存储库模式进行REST API。
我有两个通用类 baseerepository 和 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 用于启动Baseerepository及其源自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:UsersvrbatDocumentsProjectsrouter-testsrcapicommonBaseController.ts:19:13)
enter code here
我不知道为什么,因为_repository属性是在productController.ts。
挖掘后,我发现问题在于 _repository 属性的错误范围。
以下代码将修复它:
productrouter.ts
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;
}
basecontroller.ts
export class BaseController<T> implements IController {
private _repository: IRepository<T>;
constructor(repository: IRepository<T>) {
this._repository = repository;
}
getAll() {
const repository = this._repository;
return (req: Request, res: Response, next: NextFunction) => {
repository.getAll((err, result) => {
if (err)
res.send(err);
res.json(result);
});
};
}