CodeMonkey
CodeMonkey

Reputation: 3331

Angular Selective Import / Injection

Is it possible in Angular 8 to selective import / inject at runtime? I have an old service that I want to use in a new project in the same ng-cli workspace, but the new project uses the built in Angular routing, while the old one uses a 3rd party routing.

So in the constructor of the service I can do this

    let app = this.config.get('application');
    if (app == 'legacy') {
        this.state = this.injector.get<any>(StateService);
    }

Which means I don't need to inject it, but the new project code still fails because the StateService does not have provider

ERROR Error: Uncaught (in promise): NullInjectorError:
StaticInjectorError(AppModule)[StateService]:   
StaticInjectorError(Platform: core)[StateService]: 
     NullInjectorError: No provider for StateService! Error: NullInjectorError: No provider for StateService!

Which I know because I don't want to use it. Is there a way to do this without importing the 3rd party module?

Upvotes: 0

Views: 157

Answers (3)

CodeMonkey
CodeMonkey

Reputation: 3331

Turns out the code in OP was working just fine.

let app = this.config.get('application');
if (app == 'legacy') {
    this.state = this.injector.get<any>(StateService);
}

is all that is needed, the issue in my case was the if statement. (The config service was loading data from the wrong place so the if was always true)

I would add the caveat that I an using the cli generated services from angular 6+ that are provided for the root

@Injectable({providedIn: 'root'})

In case that makes any difference to people with a similar issue in the future.

Upvotes: 0

Eliran Eliassy
Eliran Eliassy

Reputation: 1600

You can always create providers in run time:

Injector.create({providers: [...]})

Upvotes: 1

Alexander
Alexander

Reputation: 3247

You can define a another provider https://angular.io/guide/dependency-injection-providers

// old project
providers: [
{ provide: StateService, useValue: OldStateService }
],

// new project
providers: [
{ provide: StateService, useValue: NewStateService }
],

Upvotes: 2

Related Questions