2017-08-31 130 views
-1

感謝您花時間閱讀本文。我剛開始使用express.js和打字稿,遇到了令我困惑的問題。我試圖弄清楚爲什麼'This'在CompanyRouter函數中是未定義的。'this'在express.js路由器中未定義路由器

路由器初始化這樣的:

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); 
    } 
} 
+0

請加錯誤,你得到。 – RaghavGarg

+0

@RaghavGarg(node:12743)UnhandledPromiseRejectionWarning:未處理的承諾拒絕(拒絕ID:1):TypeError:無法讀取未定義的屬性'服務' – puttputt

回答

0

此問題與您的方法在您的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); 
    } 
} 
+0

嗨felipe,感謝您的解決方案。這確實解決了「這個」不再被定義的問題。但路由器似乎不適用於此實現。我認爲這是由於我對express路由器缺乏瞭解。 – puttputt

+0

對不起,只是意識到這是錯誤的,你需要在中間件中傳遞正確的參數。這樣的: this.router.get('/',(req,res,next)=> this.getAllCompanies(req,res,next)); –