无法从类

时间:2019-06-11 07:03:40

标签: javascript typescript express nodes

我有一个HomeController,上面有方法索引。我在构造函数中声明了this.data变量。当我在索引方法中调用this.data时,出现类似

的错误消息

TypeError:无法读取未定义的属性“数据”

HomeController

import Controller from "./../../vendor/controller";
import * as express from "express";
import hException from "./../helper/exception.helper";

class HomeController extends Controller {
    data:object
    constructor(){
        super()
        this.data = {
            tes: 'tes'
        }
    }
    async index(request:express.Request, response:express.Response, next:express.NextFunction):Promise<any>{
        try {
            let template =  'home/index';
            //next to viewer
            response.render(template, { layout: 'dashboard', data: this.data});
        } catch (error) {
            next(new hException(error))
        }
    }
}

export default HomeController

Routes呼叫HomeController

import * as express from "express";
import Controller from "./../../controller/home.controller";

import { Jwt as MJwt } from "./../../middleware/auth.middleware";

class Routes {
    private router:express.Router = express.Router()
    private path:string = '/'
    private controller:Controller
    private MJwt = new MJwt()
    constructor() {
        this.controller = new Controller;
        this.run()
    }

    public run(){
        this.router.route(this.path)
            .get(
                this.controller.index
            );
    }
}

export default Routes

1 个答案:

答案 0 :(得分:0)

已通过用HomeController link声明arrow function方法来解决此问题,以获取详细信息。或使用绑定函数link了解详情。

Solved with arrow function