typescript + node如何从方法中获取instanse?

时间:2016-10-05 14:13:46

标签: node.js angular typescript

在服务器重建之后,compiller在包含的api控制器中创建instanse:

NewController.ts

import express        = require("express");
import INew           = require("../interface/INew");
import NewRepository  = require("../repositories/NewRepository");

class NewController {
    private _newRepository: INew;
    constructor() {
        this._newRepository = new NewRepository();
        this._newRepository.findById(5);
    }

    retrieve(req: express.Request, res: express.Response): void {
        try {
            console.log('-----------retrieve--------------------');
            this._newRepository.findById(2);
        }
        catch (e) {
            console.log(e);
        }
    }

}

Object.seal(NewController);
export = NewController;

构造函数工作:我看到控制台消息:

-------------NewRepository------------------
5 'RESULT'

NewRepository.ts:

import INew     = require("../interface/INew");
import bluebird = require("bluebird");

class NewRepository implements INew {
    sd: string;

    constructor() {
        console.log('-------------NewRepository------------------');
    }

    findById(id: number): void {
        setTimeout(function () {
            console.log(id, 'RESULT');
        }, 3000);
    }
}

export = NewRepository;

INew.ts

interface INew {
    findById: (id: number) => void;
    sd: string;
}

export = INew;

Buut当我使用控制器的方法'检索'时,访问路径'/ new'然后我得到错误[TypeError:无法读取未定义的属性'_newRepository'而不是:2'结果'

Angular 2帮助我进行路由:

.............
  getCarsRestful(): Promise<New[]> {
    console.log('-------------------------------');
    return this.http.get('api/new')
      .toPromise()
      .then(response => response.json())
      .catch(this.handleError);
  }
...................

并执行后端: NewRoutes.ts

import express       = require("express");
import NewController = require('../controllers/NewController');

  var router = express.Router();

  class NewRoutes {
    private _newController: NewController;

    constructor() {
      this._newController = new NewController()
    }

    get routes() {
      var controller = this._newController;
      router.get("/new", controller.retrieve);
      return router;
    }

  }


Object.seal(NewRoutes);
export = NewRoutes;

我创建的instanse'_newRepository'已不存在,为什么?我得到控制台日志:

-----------retrieve--------------------
[TypeError: Cannot read property '_newRepository' of undefined]

请帮助,如何在ts中制作'singltone' 我不想在每个控制器的方法中创建它,但是,它有效:

.................
retrieve(req: express.Request, res: express.Response): void {
    try {
        var _newRepository: INew;
        _newRepository = new NewRepository();
        _newRepository.findById(2);
.............

1 个答案:

答案 0 :(得分:1)

尝试在路由器配置中明确设置 this

 router.get("/new", controller.retrieve.bind(controller));