I have noticed several similar issues on this platform, but none of the solutions seem to work for me. My understanding is that because our Ng2App is bootstrapped first, it does not have a reference to $injector yet. Consequently, when I attempt to use it in my provider declaration (deps: ['$injector']), it throws an error.
What is extremely peculiar is that I can successfully utilize this service in an Angular COMPONENT, but encounter difficulties when trying to use it in an Angular SERVICE.
Here is the relevant code snippet:
import UserService from './user.service';
angular.module('app', [])
.service('UserService', UserService)
.config(/* config */)
.run(/* run */);
import './ng2app.module';
In the ng2app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { UpgradeModule } from '@angular/upgrade/static';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
@NgModule({
imports: [
BrowserModule,
UpgradeModule,
],
declarations: [],
entryComponents: [],
providers: [
// angularJS service:
{
provide: 'UserService',
useFactory: (i: any) => i.get('UserService'), // <---- this is the line all the errors point to.
deps: ['$injector']
},
]
})
export default class Ng2AppModule {
constructor(){}
}
platformBrowserDynamic()
.bootstrapModule(Ng2AppModule)
.then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.documentElement, ['app'], {strictDi: true});
});
Later... in a service (fails):
import {Injectable, Inject} from "@angular/core";
import UserService from 'app/login/user.service';
@Injectable()
export class AnAngularService{
constructor(
// causes the error if I uncomment it wtf: <--------------
// @Inject('UserService') private userService: UserService
){}
}
Later... in a component (works properly):
import { Component } from '@angular/core';
import {Inject} from "@angular/core";
import UserService from 'app/login/user.service';
import template from 'tmpl.html';
@Component({
selector: 'an-angular-component',
template,
})
export class AnAngularComponent{
constructor(
@Inject('UserService') private userService: UserService
){
console.log(userService) // works just fine. wtf <--------------
}
}
Is anyone familiar with why this issue occurs and how it can be resolved?
A similar question has been asked before, but the suggested solutions did not work for me.
AngularJS version: 1.5.8
Angular/core etc version: 4.2.4
I have also raised this issue on Github in the Angular repository for further reference.
StackTrace:
zone.js:522 Unhandled Promise rejection: Cannot read property 'get' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'get' of undefined
... (remaining stack trace details are omitted for brevity)