簡體   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