Typescript中的“ this”上下文

时间:2019-06-14 19:47:20

标签: javascript node.js typescript

我有一个具有两个功能的Controller,一个使用this调用另一个,但是当调用它时this尚未定义

举例来说,我尝试遵循these instructions,但是在我的代码中实现它时,undefined仍然如此。

控制器:

import AutenticacaoDAO from '../daos/autenticacao.dao'
import MailController from './email.controller'
import jwt from 'jsonwebtoken'
import TokenSecret from '../config/token-secret'
import crypto from 'crypto'
import { Request, Response } from 'express'
import { Usuario } from '../models/usuario.model';

class AutenticacaoController {
    constructor() {

    }

    public async login(req: Request, res: Response) {
        let usuario;
        try {
            usuario = await AutenticacaoDAO.login(req.body.email)
            this.tratarResposta(await crypto.createHash("md5").update(req.body.senha).digest("hex"), usuario) //THIS IS UNDEFINED HERE                     
    } catch (error) {
        res.json(error)
    }
}

tratarResposta (senhaEnviada: string, usuario: any) {
  // HERE I TREAT IF THE RETURNED USER IS BLOQUED OR NAH, IF THE PASSWORD 
  //IS CORRECT AND SOME OTHER STUFF
}

}

export default new AutenticacaoController()

我可以在de try语句中做我的工作(它已经起作用,我已经尝试过了),但是登录功能将太大...

我调用登录方法的路径:

import { Router } from 'express'
import AutenticacaoController from '../controllers/autenticacao.controller'


const AutenticacaoRoutes = Router()

AutenticacaoRoutes.post('/autenticacao/signup', AutenticacaoController.signUp)
AutenticacaoRoutes.post('/autenticacao/login', AutenticacaoController.login)
AutenticacaoRoutes.put('/autenticacao/esquecisenha/', AutenticacaoController.forgotPassword)
AutenticacaoRoutes.get('/autenticacao/recoverypassword/', AutenticacaoController.recoveryPassword)


export default AutenticacaoRoutes

1 个答案:

答案 0 :(得分:0)

当传递一个函数作为参数时(这就是您正在传递.login函数作为路由的中间件),您在该函数内部使用的this不再代表您的控制器。您需要指定何时调用该函数的this值。为此,您可以使用Function.prototype.bind(value)方法。

这意味着您需要进行更改

AutenticacaoRoutes.post('/autenticacao/login', AutenticacaoController.login)

AutenticacaoRoutes.post('/autenticacao/login', AutenticacaoController.login.bind(AutenticacaoController))

Here's是学习bind方法的很好参考。