简体   繁体   中英

Disable DI in Angular

I have base class (regular TS class without @Injectable() decorator) that will be extended in the service (injectable) class. But the problem is - Angular takes constructor params as Dependency Injection. And it gives me an error since base class isn't injectable.

I'd like to have something like this:

class BaseClass {
  private param1: OtherBaseClass;

  constructor(param1: OtherBaseClass) {
    // Extended class should give reference to the injected service
    this.param1 = param1;
  }
}

@Injectable({ providedIn: 'root' })
class ExtendedBaseClass {
  constructor(private extendedOtherBaseClass: ExtendedOtherBaseClass) {
    super(extendedOtherBaseClass);
  }
}

Of course, that DI disabling should affect only base classes, not the whole app.
Is that possible?
Making base classes injectable isn't an option since I won't be able to overwrite methods in the extended class.

Okay, looks like I found the answer.
I can set @Injectable() decorator for the base class without { providedIn: 'root' } (and without adding this class to the module's providers). It allows you to have inject syntax within the base class constructor (that will be "overwritten" in the extended class), but, in the same time, overwritten methods will work in the extended class too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM