Koa(nodejs)/ TS控制器,错误:无法读取未定义的x

问题描述 投票:0回答:1

我在后面有打字稿,并有一个电子邮件控制器,该电子邮件控制器是一个类,然后执行各种操作,将数据传递给该类,但在尝试初始化另一个类时不起作用。

email.router.ts

import Router from 'koa-router';
const router = new Router();
import { Email } from '../Controllers/sendEmail.controller';
const email = new Email();
console.log('email class', email); // all data there

router.post('/resetPassword', email.resetPassword);

export default router.routes();

电子邮件类别

export class Email {
  public conn: any = new Connection(); // all data there

  public constructor() {
    this.conn = this.conn;
    console.log('in constructor of email', this.conn); // all data there
  }

  public async resetPassword(ctx: Context): Promise<void> {
    console.log('email -->', ctx.request.body); // passed by reference correctly
    console.log('conn -->', this.conn); // error*
  }
}

连接类别

export class Connection {
  public smtpHost = 'host';
  public smtpPort = 1231273612;
  public smtpSecure = boolean;
  public smtpUser = '[email protected]';
  public smtpPass = 'someSuperSecretPassword';

  public token: string;

  public constructor(token?: string) {
    this.token = token;
  }

  public message(): string {
    return (
      `string with ${this.token}`
  }
}

错误* TypeError: Cannot read property 'conn' of undefined

我为自己的生命而奋斗。...这是stack blitz

node.js typescript koa koa2
1个回答
0
投票

您需要绑定this参数。要么:

router.post('/resetPassword', ctx => email.resetPassword(ctx));

或:

router.post('/resetPassword', email.resetPassword.bind(email));
© www.soinside.com 2019 - 2024. All rights reserved.