Nest: Can't inject with property-based injection.

Created on 6 Nov 2018  路  6Comments  路  Source: nestjs/nest

I have one class extend another one.
In order not to drag dependency through constructor and super I try to inject via property injection.

From docs:

Property-based injection
In some very specific cases, a property-based injection might be useful. For instance, if your top-level class depends on either one or multiple providers, passing them all the way up by calling super() in sub-classes from the constructor can be very annonying. Thus, in order to avoid it, you can use @Inject() decorator on a property level.

import { Injectable, Inject } from '@nestjs/common';

@Injectable()
export class HttpService<T> {
  @Inject('HTTP_OPTIONS')
  private readonly httpClient: T;
}

I'm trying to replace this:

  public constructor(
    private configService: ConfigService
  ) {
    super();
  }

with this:

@Inject(ConfigService) private readonly configService: ConfigService;
// or this
@Inject('CONFIG_SERVICE_PROVIDER') private readonly configService: ConfigService;

But there is ts error:
TS1240: Unable to resolve signature of property decorator when called as an expression.

And configService undefined.

image

All 6 comments

Maybe it's worth to expose static get like in angular. So you can do something like:

  private configService: ConfigService;

  constructor() {
    this.configService = Injector.get(ConfigService);
  }

https://github.com/nestjs/nest/issues/1014
@kamilmysliwiec yet another reason to use Inversify as I've stated multiple times...

@ph55

this should work

import { Injector } from '@nestjs/core'; 

@Injectable()
abstract class BaseService {
  protected readonly core: CoreService;

  constructor(injector: Injector) {
    this.core = injector.get<CoreService>(CoreService);
  }
}

@Injectable()
export class FirstService extends BaseService {
  // this.core should be an instance of CoreService
}

Above solution won't work because there is no Injector, instead, we have ModuleRef class. However, @ph55 it looks that you haven't updated your packages yet. Please, upgrade to 5.4.0 and issues will disappear.

Oh, I see. It only introduced in latest 5.4

So I guess origin of confusion is that documentation not versioned.
There is even feature request for it already - https://github.com/nestjs/docs.nestjs.com/issues/64

Thanks.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mishelashala picture mishelashala  路  3Comments

rlesniak picture rlesniak  路  3Comments

tronginc picture tronginc  路  3Comments

2233322 picture 2233322  路  3Comments

JulianBiermann picture JulianBiermann  路  3Comments