Koa(nodejs)/TS Controller, Error: cannot read x of undefined

Koa(nodejs)/TS Controller, Error: cannot read x of undefined

我在后面有 typescript 和一个电子邮件控制器,那个电子邮件控制器是一个 class 然后做各种事情,将数据传递给 class 作品,但是,当试图初始化另一个 class.

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();

电子邮件Class

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*
  }
}

连接Class

export class Connection {
  public smtpHost = 'host';
  public smtpPort = 1231273612;
  public smtpSecure = boolean;
  public smtpUser = 'foo@bar.com';
  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

您需要绑定this参数。或者:

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

或:

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

如果你认真对待 Koa v2+ 中的 Typescript 控制器,绝对可以考虑查看 https://github.com/iyobo/koa-ts-controllers