节点和打字稿:属性 调用路由时未定义

node and typescript: property undefined when call route

我决定创建一个没有任何 ORM 的项目,只使用 mysql2 包 + 节点(打字稿),但我很难解决下面的问题:

TypeError: Cannot read property 'userService' of undefined

当我尝试调用 get 路由 /api/user 时出现此错误,但服务正在我的控制器 class 上初始化。我只测试了查询并按预期返回所有内容。

我的项目的主要结构将有一个用于数据库查询的 repository,一个用于业务逻辑的 service 和一个 controller 将管理我的路线。

用户资料库

import pool from './../config/db';

interface IUser {
    id: number,
    login: string,
    created_at: Date,
    updated_at: Date
}

class User {
    async getUsers (): Promise<Array<IUser>> {
        try {
            const [rows]: [Array<IUser>] = await pool.query('SELECT * FROM `clients`', []);
            return rows;
        } catch (err) {
            return err;
        }
    }
}

export default User;

用户服务

import User from './../repository/user';

class UserService {
    private user;

    constructor () {
        this.user = new User();
    }

    getUsers () {
        return this.user.getUsers();
    }
}

export default UserService;

用户控制器

import UserService from '../services/user.service';
import express from 'express';

class UserController {
    public path = '/user';
    public router = express.Router();
    public userService;

    constructor () {
        this.userService = new UserService();
        this.initializeRoutes();
    }

    private initializeRoutes (): void {
        this.router.get(this.path, this.get);
    }

    get (req, res) {
        res.send(this.userService.getUsers());
    }
}

export default UserController;

在我的主文件中,我有调用路由的方法:

  private routes (): void {
        const routes = [
            new UserController()
        ];

        routes.forEach((route) => {
            this.app.use('/api', route.router);
        });
    }

在UserController中,get class方法函数被路由器调用。所以你应该将 get 函数绑定到 class 实例映射器,所以到 this 就像这样:

  constructor() {
    this.userService = new UserService();
    this.get = this.get.bind(this); // here you bind the function
    this.initializeRoutes();
  }