javascript - İthal Edilmiş Bir Sınıftan Bir Metodu Çağırdığımda undefined özelliğini okuyamıyor - TypeError [TypeScript]
Bunu birkaç saat boyunca hata ayıkladıktan sonra, çevrimiçi olarak da hiçbir şey bulamadım..
Veriyi geri almak için bir servis metodunu çağıran bir denetleyicim var:
Rota: routes/inspections.ts
import {Request, Response} from "express";
import { InspectionsController } from "../controllers";
export class Routes {
public inspectionsController: InspectionsController = new InspectionsController()
public routes(app): void {
// Inspection detail
app.route('/data/inspections/:inspectionId')
// get specific inspection
.get(this.inspectionsController.getInspectionByID)
// Inspection detail
app.route('/data/inspections')
// get specific inspection
.get(this.inspectionsController.getInspections)
}
}
Kontrolcü: controllers/inspections.ts
import { Request, Response } from 'express';
import { InspectionsService } from '../services/inspections';
export class InspectionsController {
public inspectionsService: InspectionsService = new InspectionsService();
public async getInspections (req: Request, res: Response) {
try {
const response = await this.inspectionsService.getInspections();
res.json(response);
}catch (e) {
console.log(e.toString())
}
}
public getInspectionByID (req: Request, res: Response) {
res.json('You reached getInspectionByID in the controller Wohoooo!');
}
}
Hizmet: services/inspections.ts
export class InspectionsService {
public async getInspections(){
return 'You reached getInspections in the service Wohoooo!';
}
}
Benim problemim, programımın sadece controller seviyesine ulaşıp servise ulaşmaması. Aşağıdaki hata mesajını alıyorum:
TypeError: Cannot read property 'inspectionsService' of undefined
Şimdiden çok teşekkürler arkadaşlar, her türlü yardım gerçekten takdir edilir!
Cevap #1
Sorunun, inspectionsController.getInspections'in yönlendiricinizde çağrıldığı bağlamla ilgili olabileceği görünüyor.
Belki yönlendiricinize aşağıdaki değişiklikleri yapabilirsiniz, böylece getInspections, Routes örneğinizin bağlamından çağrılır - bu değişiklikler sizin için işe yarıyor mu?
export class Routes {
public inspectionsController: InspectionsController = new InspectionsController()
public routes(app): void {
// Inspection detail
app.route('/data/inspections/:inspectionId')
// get specific inspection
.get(this.inspectionsController.getInspectionByID)
// Inspection detail
app.route('/data/inspections')
// get specific inspection
.get((req: Request, res: Response) => {
// UPDATE: Move the invocation of getInspections() into an arrow function
// so that the "this" context is that of the Routes instance
this.inspectionsController.getInspections(req, res)
})
}
}
Cevap #2
Bunu kontrolcünüzde deneyin,
constructor(private inspectionsService: InspectionsService) {}
public getInspections(){
return new Promise(resolve => {
setTimeout(() => {
resolve('You reached getInspections in the service Wohoooo!');
}, 2000);
});
}