FoalTS / foal

Full-featured Node.js framework, with no complexity. 🚀 Simple and easy to use, TypeScript-based and well-documented.
https://foalts.org/
MIT License
1.9k stars 140 forks source link

injected instances of abstract service are `undefined` #818

Closed LorenzKahl closed 3 years ago

LorenzKahl commented 3 years ago

Hi, I am new to FoalTS / Cryos and have a newly scaffolded project using the CLI. I followed along the documentation on abstract services step by step but when I'm trying to use the injected instance of the Logger it is undefined.

// src/app/app.controller.ts

import { controller, dependency } from '@foal/core';
import { ApiController } from './controllers';
import { Logger } from './services';

export class AppController {
  @dependency
  logger: Logger;

  subControllers = [
    controller('/api', ApiController)
  ];

  constructor() {
    this.init();
  }

  init = () => {
    console.log('AppController / init', this.logger);
  };
}

Running npm run develop will render the following to the console:

[0] 22:51:25 - Found 0 errors. Watching for file changes. [1] crashing child [1] Starting child process with 'node ./build/index.js' [1] AppController / init undefined [1] Listening on port 3001...

Am I missing something really basic or is something actually broken?

BTW: I'm on the latest version of FoalTS.

LoicPoullain commented 3 years ago

Hi @LorenzKahl and welcome to FoalTS/Cryos community.

Constructors cannot be used to access injected instances because they are injected after the instantiation of the controllers/services.

The best way to initialization the application or a service is to use the init or boot methods instead following this part of the docs: https://foalts.gitbook.io/docs/topic-guides/architecture/initialization

Hope this helps!

LorenzKahl commented 3 years ago

Hi @LoicPoullain, thanks for the warm welcome and for pointing me in the right direction. How could I miss that? It's so well documented.

Still, you might consider adding a forward reference at the top of the Use & Dependency Injection section to the Initialization page pointing out that the reader will find the necessary steps there in order to make this fly.

Thanks again & best regards!

LoicPoullain commented 3 years ago

Thank you for the advice @LorenzKahl . The doc has been updated.