chriskohler
chriskohler

Reputation: 165

Why is the $injector empty when using UpgradeComponent

I try to upgrade from angular1 to angular2 by bootstraping hybrid both ng1 and ng2.

Here is the code: https://plnkr.co/edit/3jrnPyVc8WN2a4crUJFp?p=preview

When I run this example I get an error saying:

 Cannot read property 'get' of undefined
at HeroDetailDirective.UpgradeComponent (https://unpkg.com/@angular/upgrade/bundles/upgrade-static.umd.js:512:43)
at new HeroDetailDirective (https://run.plnkr.co/QOdaB9QdPbHLfQe9/app/main.0.ts!transpiled:45:16)
at new Wrapper_HeroDetailDirective (/AppModule/HeroDetailDirective/wrapper.ngfactory.js:7:18)

When I debug I see that in the UpgradeComponent the $injector is empty:

function UpgradeComponent(name, elementRef, injector) {
        this.name = name;
        this.elementRef = elementRef;
        this.injector = injector;
        this.controllerInstance = null;
        this.bindingDestination = null;
        this.$injector = injector.get($INJECTOR);

Any ideas why?

Thank you for your help.

Upvotes: 2

Views: 520

Answers (1)

chriskohler
chriskohler

Reputation: 165

Found the problem.

I defined to bootstrap the AppComponent:

@NgModule({
  imports: [ BrowserModule, UpgradeModule ],
  declarations: [ AppComponent, HeroDetailDirective ],
  bootstrap: [  AppComponent  ]
})
class AppModule {
  ngDoBootstrap() {}
}

When I removed the bootstrap definition, it worked:

@NgModule({
  imports: [ BrowserModule, UpgradeModule ],
  declarations: [ AppComponent, HeroDetailDirective ]
})
class AppModule {
  ngDoBootstrap() {}
}

I didn't realise that a hybrid app is always bootstrapped by ng1. This articel helped me a lot: https://www.softwarearchitekt.at/post/2016/11/15/using-ngupgrade-with-aot-to-optimize-performane.aspx

Upvotes: 1

Related Questions