Controllers, why doesn't possible inject services? #645
-
import { RouterContext, Row } from "@deps";
import { IPerson } from "../../interfaces/IPerson.ts";
import registerService, { RegisterService } from "../../services/register.ts";
const register: RegisterService = registerService; // THIS WORKS FINE
export class RegisterController {
registerService: RegisterService ;
constructor() {
this.registerService = registerService; // OR new RegisterService(); Doesn't works
}
public async registerPerson(ctx: RouterContext<string>, next: () => Promise<unknown>): Promise<Row> {
next();
const body = await ctx.request.body({ type: 'json' }).value;
console.log(this.registerService) // BUT THIS NOTS WORK
const register = await registerService.create(body);
if (!register.isCreated) throw new Error("Error to register person");
ctx.response.type = "json"
ctx.response.status = 201;
return ctx.response.body = register.person;
}
} Throw this error: [uncaught application error]: TypeError - Cannot read properties of undefined (reading 'registerService')
request: { url: "http://0.0.0.0:8080/register", method: "POST", hasBody: true }
response: { status: 404, type: undefined, hasBody: false, writable: true } I've already tried to inject it as a dependency, I've tried to instantiate the class before putting it in the controller, I've tried a lot of things and it didn't work
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Now that I have more experience in JavaScript, I remember hearing that JavaScript doesn't have classes natively, it works with prototypes. Then I also remembered that when you have callbacks using this, JavaScript can get lost as to who this is. Then I remembered .bind() or inferring in the routing the correct call of the object together with the method that returns something. So this doesn't get lost. |
Beta Was this translation helpful? Give feedback.
Now that I have more experience in JavaScript, I remember hearing that JavaScript doesn't have classes natively, it works with prototypes.
Then I also remembered that when you have callbacks using this, JavaScript can get lost as to who this is.
Then I remembered .bind() or inferring in the routing the correct call of the object together with the method that returns something.
So this doesn't get lost.