0

I was trying to create an endpoint in node.js, more specifically in express but I am not sure why I can't access userService variable when requesting from a client.

I've gotten Cannot read property 'userService' of undefined, but when i move ServicesFactory.getInstance().getUserService() inside the signUp function it works?! I am guessing that node.js garbage collects it due to it's not being used until the user make a request.

export class UserApi implements WebEndpoint {

    router: Router
    userService = ServicesFactory.getInstance().getUserService()

    constructor() {
        this.router = Router()
        this.router.post('/signup', this.signUp)
    }

    signUp(req: Request, res: Response): void {
        const user: User = req.body
        this.userService.signUp(user)
        res.send("Successfully registered")
    }

}
A N Syafiq.
  • 143
  • 1
  • 3
  • 12

1 Answers1

0

I found the problem, so basically I am a noob. consider this example

class a {
    constructor() {
        this.a1 = 'hello';
    }

    greet(){
        const greeting = `${this.a1} dude!`;
        console.log(greeting);
    };
}

class b {
    b1 = new a();

    constructor() {
        this.b1.greet.call();
    }
}

new b();

Now it wouldn't run, because b class called greet method with a new context, the same with express when you provide a function as a handler on an Express endpoint it will be called with a new set of context (read:this) that's why this.userService in my code above won't work because there is no userService property in the context provided by Express.

The solution is simple. Arrow function.

 signUp = (req: Request, res: Response): void => {
        const user: User = req.body
        this.userService.signUp(user)
        res.send("Successfully registered")
    }

Now the function will inherit it's class's context.You can refer to this for more detail answer.

A N Syafiq.
  • 143
  • 1
  • 3
  • 12