moizKachwala / Angular2-express-mongoose-gulp-node-typescript

AngularJS 2 (Updated to 4.2.0) Mean Stack application which uses Angular2, Gulp, Express, Node, MongoDB (Mongoose) with Repository Pattern Business Layer
MIT License
196 stars 86 forks source link

Property in Controller class can't used in the functions which are register in Routes #22

Closed zzczzc004 closed 7 years ago

zzczzc004 commented 7 years ago

I want to add a property in the Controller class. Like in the HeroController, I add a 'test' property, and I want to use it in the create function. But when create is invoke by the route, it show [TypeError: Cannot read property 'test' of undefined].

I think it's because typescript is simulate class but Javascript didn't have a class until ES6. I have use c# before and use Javascript and Typescript recently but not full understand it.

class HeroController {

    test = "test";

    create(req: express.Request, res: express.Response): void {
        console.log(this.test);
    }
}
zzczzc004 commented 7 years ago

I found I got an incorrect understanding about keywords this before, and solved the problem by change the way of register controller in the Routes. Before: router.post("/heroes", controller.create); After: router.post("/heroes", (req, res) => controller.create(req, res));

zzczzc004 commented 7 years ago

I found 'this' in TypeScript is a common problem, here are some useful blog and wiki about understand it and how to avoid it.

moizKachwala commented 7 years ago

glad you got the resolution :)