Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an NgUpgrade app where I'm migrating from Angular.js's UI-Router to Angular's Router and everything was going well until I introduced a lazy-loaded module. Then, in one of the components from the lazy-loaded module I got this:

Found an error while navigating to /my-lazy-feature error: TypeError: Cannot read property 'get' of undefined
    at new MyComponent (my.component.ts:86)
    at NodeInjectorFactory.MyComponent_Factory [as factory] (my.component.ts:147)
    at getNodeInjectable (core.js:3503)
    at instantiateAllDirectives (core.js:9988)
    at createDirectivesInstances (core.js:9337)
    at Module.??elementStart (core.js:14559)
    at MyOtherComponent_Template (my-other.component.ts:21)
    at executeTemplate (core.js:9310)
    at renderView (core.js:9117)
    at renderComponent (core.js:10392)
    at renderChildComponents (core.js:8982)
    at renderView (core.js:9142)
    at ComponentFactory$1.create (core.js:24837)
    at ViewContainerRef.createComponent (core.js:22876)
    at RouterOutlet.activateWith (router.js:5182)

This error is generated in the expression upgrade.$injector.get, in which I try to get a reference to one of the Angular.js services:

@Component(...)
export class MyComponent implements OnInit {
    constructor(upgrade: UpgradeModule) {
        this.state = upgrade.$injector.get("$state");
        this.stateParams = upgrade.$injector.get("$stateParams");
    }

From inside MyComponent I do console.log(upgrade) and I see there is no upgrade.$injector, but if I do the same from a non-lazy-loaded module, I see $injector is defined ok.

So there seem to be 2 instances of UpgradeModule. What can be the reason of this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem ended up being, the lazy-loaded module was importing a module that was importing UpgradeModule, thus creating a second instance.

To fix it, ensure you only import UpgradeModule in the main module of your application. Even if your other modules need to access UpgradeModule, there is only need to import it once.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...