感謝您花時間閱讀本文。我剛開始使用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);
}
}
請加錯誤,你得到。 – RaghavGarg
@RaghavGarg(node:12743)UnhandledPromiseRejectionWarning:未處理的承諾拒絕(拒絕ID:1):TypeError:無法讀取未定義的屬性'服務' – puttputt