我在后面有打字稿,并有一个电子邮件控制器,该电子邮件控制器是一个类,然后执行各种操作,将数据传递给该类,但在尝试初始化另一个类时不起作用。
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
您需要绑定this
参数。要么:
router.post('/resetPassword', ctx => email.resetPassword(ctx));
或:
router.post('/resetPassword', email.resetPassword.bind(email));