0

I have a root module that lazily loads another module. In this lazily loaded module, a route has a resolver that tries to load some external data. If it fails, it stores an error message in itself, and navigates to an error component. The error component has the resolver injected, and then should display the error message from the resolver.

I have adapted the official Angular 2 Tour of Heroes as an example in the following ways:

  • app/crisis-center/crisis-detail-resolver.service.ts - Modified to always set the errorMessage field, and navigate to the ErrorComponent. This previously navigated to the /crisis-center command.
  • app/crisis-center/error.component.ts - Newly added. Takes the CrisisDetailResolver as a dependency, and displays the errorMessage from it.

If the crisis-center.module.ts is lazily loaded, the resolver injected in to ErrorComponent is not the same as the resolver used in the router. I can only confirm this by the absence of errorMessage in the resolver when debugging. You can see this on plnkr by clicking on any crisis under the crisis center. You'll see no error message being displayed.

If the module is not lazily loaded (i.e. I load it explicitly in the root module), the resolver is now a singleton and I have the error message to display in the ErrorComponent. You can see this on plnkr by clicking on any crisis under the crisis center. You'll see an error message displayed.

I'm confused as to why this isn't working, as far as I'm aware, the CrisisDetailResolver is declared to be a singleton in the provider block of app/crisis-center/crisis-center-routing.module.ts.

2 Answers 2

1

In case anyone stumbles on this problem, I've found that my problem is caused by an issue in Angular and should be addressed soon.

The issue is that the current version if Angular 2 (2.4.1) will create a new module (and consequently a new injector) with each navigation. This is why my providers were not being kept as singletons.

The GitHub issue I raised can be found here, and contains a much more in-depth explanation of the problem: https://github.com/angular/angular/issues/13722

Sign up to request clarification or add additional context in comments.

Comments

0

As per documentation, providers for lazy-loaded modules are module scoped. It looks like your case: https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-lazy-loaded-module-provider-visibility

1 Comment

Hi, I've read that before, but my resolver service is declared in the provider block of the module that is being lazily loaded. The resolver service is only used inside this module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.