Search code examples
angulardependency-injectionangular-hybrid

Angular 8 Dependency Injection Without TypeScript?


I'm currently following tutorials for migrating an AngularJS (1.5.x) app to an AngularJS / Angular 8 hybrid. It's been decided that we will not use TypeScript just yet, and will stick to JavaScript transpiling with Babel. I can't seem to find anything about dependency injection in Angular without TypeScript.

app.module.js

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { UpgradeModule } from '@angular/upgrade/static';
import AppComponent from './app.component';
import angularJsModule from '../app/scripts/app';

@NgModule({
    imports: [
        BrowserModule,
        UpgradeModule
    ]
})

export default class AppModule {
    constructor(upgrade) {
        console.log('angular 8 plz?');
    }

    ngDoBootstrap() {
        this.upgrade.bootstrap(document.body, [angularJsModule.name], { strictDi: true });
    }
}

Upon running the application, I receive Uncaught Error: Can't resolve all parameters for AppModule: (?).

I assume this is because the UpgradeModule isn't being injected because of the lack of TypeScript? https://angular.io/guide/dependency-injection#dependency-injection-tokens

I've tried setting this.upgrade = upgrade inside the constructor, but this is never reached because Angular doesn't know what upgrade is.

Is there a way to inject UpgradeModule without TypeScript?

Or is the error I'm encountering because of something different?


Solution

  • You have to use Inject

    Import:

    import { NgModule, Inject } from '@angular/core';
    

    Changed constructor:

    constructor(@Inject(UpgradeModule) upgrade) {
      this.upgrade = upgrade;
    }