【发布时间】:2021-10-13 18:17:14
【问题描述】:
我对 typescript 和 node.js 比较陌生,但我想学习一些东西并尝试一些新的东西,包括 angular、node 和 express。我仍然尝试找到一些好的做法来将 express 项目拆分为几个较小的部分,但不知何故我遇到了问题。我想创建一个抽象的 Controller 类和一些子类,它们将是由 express.Router() 支持的典型 REST 控制器。
这是基类 - 控制器:
import express, {Router} from "express";
export abstract class Controller {
public router = express.Router();
public path: string;
protected constructor(path: string) {
this.path = path;
console.log('Calling initializeRoutes() from superclass');
this.initializeRoutes();
}
abstract initializeRoutes(): void;
}
还有子类 - 这只是一个例子 - UserController 类:
import {Controller} from "./Controller";
import express from "express";
export class UserController extends Controller {
private users = [
{name: 'User1', password: 'password1'},
{name: 'User2', password: 'password2'},
{name: 'User3', password: 'password3'}
]
constructor(path: string) {
super(path);
console.log('Calling initializeRoutes() from subclass');
this.initializeRoutes();
}
initializeRoutes(): void {
// console.log(this.router);
console.log(this.getAllUsers);
console.log(this.createAPost);
// this.router.get(this.path, this.getAllUsers);
// this.router.post(this.path, this.createAPost);
}
getAllUsers = (request: express.Request, response: express.Response) => {
response.send(this.users);
}
createAPost = (request: express.Request, response: express.Response) => {
const user = request.body;
this.users.push(user);
response.send(user);
}
主要问题是我想在基类中调用initializeRoutes(),但是当我这样做时会抛出错误,即我不能在路由器中使用未定义的回调。我做了一些调试,发现当在基类中使用 initializeRoutes() 时,来自子类的回调是未定义的,而从子类运行时一切正常:
[1] [nodemon] starting `ts-node server\server.ts`
[1] Calling initializeRoutes() from superclass
[1] undefined
[1] undefined
[1] Calling initializeRoutes() from subclass
[1] [Function (anonymous)]
[1] [Function (anonymous)]
这是为什么呢?我做错了什么或错过了什么? 提前致谢
编辑:我尝试了建议的解决方案:
export class UserController extends Controller {
constructor(path: string) {
super(path);
this.getAllUsers = this.getAllUsers.bind(this);
this.createAPost = this.createAPost.bind(this);
console.log('Calling initializeRoutes() from subclass');
// this.initializeRoutes();
}
initializeRoutes(): void {
// console.log(this.router);
this.getAllUsers = this.getAllUsers.bind(this);
this.createAPost = this.createAPost.bind(this);
console.log(this.getAllUsers);
console.log(this.createAPost);
this.router.get(this.path, this.getAllUsers);
this.router.post(this.path, this.createAPost);
}
}
当我将其放入 initializeRoutes() 时,我得到:
[1] TypeError: Cannot read property 'bind' of undefined [1] at UserController.initializeRoutes (C:\Blazej\Projects\pasteur\server\controller\UserController.ts:19:41)
当我将它放入构造函数时,我得到:
[1] Error: Route.get() requires a callback function but got a [object Undefined]
【问题讨论】:
标签: node.js typescript inheritance callback