【问题标题】:TypeError: Cannot read property 'User' of undefined in typescript codeTypeError:无法读取打字稿代码中未定义的属性“用户”
【发布时间】:2019-12-15 09:52:41
【问题描述】:

我无法访问 typescript 类的用户私有属性


import { Request, Response } from 'express'
import UserModel from '../models/UserModel'

class UserController {
  private User: UserModel[] = [
    {
      id: 1,
      name: 'Test 1',
      email: 'test1@test.com.br'
    },
    {
      id: 2,
      name: 'Test2 2',
      email: 'test2@test.com.br'
    }
  ]

  /**
   * [GET] /users
   * @param req: Request
   * @param res: Response
   */
  public async index (req: Request, res: Response): Promise <Response> {
    return res.json(this.User)
  }
}

export default new UserController()

当我访问路由 [GET] /users 时,我遇到了“TypeError: Cannot read property 'User' of undefined”错误。 我正在使用异步方法,因为在不久的将来,这条路线将连接到数据库,现在我正在使用静态用户测试该类。 我该如何解决?谢谢

【问题讨论】:

  • 我认为这是因为您试图以公共方法访问私有字段,请将用户更改为公共。
  • @Clarity private 意味着它不能从外部类的方法中获得
  • 我尝试从私有更改为公共,但结果是一样的

标签: javascript node.js typescript express


【解决方案1】:

index 方法使用箭头函数以确保this 绑定到您的UserController 实例:

public index = async (req: Request, res: Response): Promise <Response> => {
  return res.json(this.User)
}

或者,您可以使用已有的并将index 方法绑定到构造函数中的实例:

class UserController {
  private User: UserModel[] = [
    {
      id: 1,
      name: 'Test 1',
      email: 'test1@test.com.br'
    },
    {
      id: 2,
      name: 'Test2 2',
      email: 'test2@test.com.br'
    }
  ]

  constructor() {
    this.index = this.index.bind(this)
  }

  /**
   * [GET] /users
   * @param req: Request
   * @param res: Response
   */
  public async index (req: Request, res: Response): Promise <Response> {
    return res.json(this.User)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多