'this'在express.js路由器中未定义

时间:2017-08-31 16:53:08

标签: typescript express

感谢您花时间阅读本文。我刚刚开始使用express.js和打字稿,遇到了令我困惑的问题。我试图弄清楚为什么'this'在CompanyRouter函数中是未定义的。

路由器初始化如下:

this.express.use('/api/v1/company', new CompanyRouter(new CompanyService()).router);

是上下文问题,还是express.js将路由器功能视为静态功能?

import {Router, Request, Response, NextFunction} from 'express';
import {Company} from '../models/Company';
import {ICompanyService} from '../interfaces/ICompanyService';

export class CompanyRouter {
    router: Router
    service: ICompanyService

    constructor(service : ICompanyService) {
        this.router = Router();
        this.service = service;
        this.init();
    }

    init() {
        this.router.get('/', this.getAllCompanies);
        this.router.post('/', this.postCompany);
    }

    public async getAllCompanies(req: Request, res: Response, next: NextFunction) {
        const companies = this.service.findAll()
        res.send(companies);
    }

    public async postCompany(req: Request, res: Response, next: NextFunction) {
        const company = this.service.add(req.body);
        res.send(company);
    }
}

1 个答案:

答案 0 :(得分:1)

此问题与您在init()函数中调用方法的方式有关。传递函数的引用而不是直接调用它将使this未定义,因为它丢失了它的引用。

所以,我认为以下代码应该有效:

import {Router, Request, Response, NextFunction} from 'express';
import {Company} from '../models/Company';
import {ICompanyService} from '../interfaces/ICompanyService';

export class CompanyRouter {
    router: Router
    service: ICompanyService

    constructor(service : ICompanyService) {
        this.router = Router();
        this.service = service;
        this.init();
    }

    init() {
        this.router.get('/', (req, res, next) => this.getAllCompanies(req, res, next));
        this.router.post('/', (req, res, next) => this.postCompany(req, res, next));
    }

    public async getAllCompanies(req: Request, res: Response, next: NextFunction) {
        const companies = this.service.findAll()
        res.send(companies);
    }

    public async postCompany(req: Request, res: Response, next: NextFunction) {
        const company = this.service.add(req.body);
        res.send(company);
    }
 }