我在访问派生类中的成员时遇到问题。我正在将node.js与typescript和expressjs结合使用,mountRoutes()
将控制器的功能添加到了主要的express应用中。我可以访问派生类的构造函数中的成员,但不能访问express调用的函数中的成员。有谁知道我该如何解决这个问题。
谢谢。
基类
import { Router } from "express";
export abstract class Controller {
protected mRouter: Router;
protected readonly mName: string;
public constructor(controllerName: string) {
this.mRouter = Router();
this.mName = controllerName;
}
// Public interface for router
get router(): Router {
return this.mRouter;
}
// Public interface for router
get name(): string {
return this.mName;
}
// Mount routes of controller
protected abstract mountRoutes(): void;
// Get error ID for error
protected error_id(error_id1: number): string {
return 'Controller ' + this.mName + ': ' + error_id1.toString();
}
}
和派生类: 从“ ./controller”导入{Controller};
import { Response, NextFunction } from 'express';
import { DatabaseService } from "../database/database.service";
class UserController extends Controller {
constructor() {
super('user');
this.mountRoutes();
}
protected mountRoutes(): void {
this.mRouter.get('/', this.getUsers);
}
private getUsers(request: any, response: Response, next: NextFunction): void {
console.log(this.mName); // HERE: this is UNDEFINED
}
}
export default new UserController().router;