使用express和typescript的RESTful服务 - 这对于Response.send()

时间:2017-06-06 21:13:21

标签: node.js rest express typescript

似乎在express.Response.send()方法中未定义“this”。有没有办法继续发送我的路由器成员?

MY-router.ts:

import { Router, Request, Response, NextFunction } from 'express';
import { MyTsObject } from "../my-ts-object";

export class MyRouter {
    router: Router;
    myTsObject: MyTsObject;

    constructor() {
        this.myTsObject = new MyTsObject();
        this.router = Router();
        this.init();
    }

    public getData(req: Request, res: Response, next: NextFunction){
        res.send(JSON.stringify(this.myTsObject)); // runtime error here:
        // TypeError: Cannot read property 'myTsObject' of undefined
    }

    init() {
        this.router.get('/', this.getData);
    }
}

app.ts:

import * as express from 'express';
import * as logger from 'morgan';
import * as bodyParser from 'body-parser';
import { MyRouter } from "./routes/my-router";

class App {
    public express: express.Application;

    constructor() {
        this.express = express();
        this.middleware();
        this.routes();
    }

    private middleware(): void {
        this.express.use(logger('dev'));
        this.express.use(bodyParser.json());
        this.express.use(bodyParser.urlencoded({ extended: false}));
    }

    private routes(): void {
        this.express.use('/', new MyRouter().router);
    }

}

export default new App().express;

index.ts:

import * as  http from 'http';
import * as debug from 'debug';

import App from './app';

debug('ts-express:server');

const port = normalizePort(process.env.PORT || 3000);
App.set('port', port);

const server = http.createServer(App);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

....

请参阅my-router.ts文件,了解我在浏览器中点击网址时发生的运行时错误。我假设'this'在该上下文中不是指MyRouter对象。还有办法从send()方法中获取对myTsObject的引用吗?有没有更好的方法来做这一切?

1 个答案:

答案 0 :(得分:1)

您可以在getData方法中将MyRouter方法的上下文绑定到init

init() {
    this.router.get('/', this.getData.bind(this));
}

或者,您可以将匿名函数传递给实现相同功能的router.get

init() {
    this.router.get('/', (req: Request, res: Response, next: NextFunction) => this.getData(req, res, next));
}