繁体   English   中英

节点和 typescript:调用路由时属性未定义

[英]node and typescript: property undefined when call route

我决定创建一个没有任何 ORM 的项目,只使用 mysql2 package + node(typescript),但我很难在下面找出这个问题:

TypeError: Cannot read property 'userService' of undefined

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

我的项目的主要结构将有一个用于数据库查询的存储库、一个用于业务逻辑的服务和一个用于管理我的路线的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方法function。 所以你应该绑定get function 到 class 实例映射器, this像这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM