I'm using angular 2 lazy routing. Client is bundled with webpack2 using AOT and angular-router-loader to lazy load children. Everything works as expected when the browser is connected, that is I can successfully navigate the router to the lazy loaded module, the chunk is loaded successfully and I can view the component etc.
However if I emulate being disconnected (e.g by using the Offline chrome developer tools option) routing fails, as expected, because it can't load the relevant chunk. The error is 'Loading chunk [chunk number] failed'
After that no routing command works, it's like the router is broken.
I tried to handle the error using a global ErrorHandler. The idea was that perhaps I could catch the error before it breaks the router, but it seems that it is too late by then. At the time I catch the error the router is not working.
import { Injectable, ErrorHandler, Injector } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class CustomErrorHandler extends ErrorHandler {
constructor(private injector: Injector) {
super(false);
}
private get router(): Router {
return this.injector.get(Router, null);
}
public handleError(error: Error) {
if (/Loading chunk [\d]+ failed/.test(error.message)) {
console.info('Offline mode');
let router = this.router;
if (router) {
router.navigateByUrl('/offline').then(t => console.debug(t+'')).catch(t=> console.debug(t));
} else {
window.location.href = '/';
}
}
}
}
The Custom error handler works because the 'Offline mode' message is printed. Injection also works, router is not null, however router navigation does not work, the router promise is not resolved neither rejected.
What I'm trying to accomplish is to handle the error (e.g. to show an informative message to the user) and at the same time having the router at a working state, so that the user can navigate later (when internet connection is restored) without reloading the whole page.
Update 1: trying to reproduce without aot and webpack
In order to see if this is an angular router issue I tried to see what happens when trying to work offline with jit compilation. I used the : angular router plunker navigated to login tab, switched to offline and pressed login. A number of 'Error: XHR error loading' errors were logged as the client was trying to load the admin module. Ultimately navigation failed, however routing navigation did not break after that. I was able to navigate to other tabs and after switching back online I was even able to navigate to admin. Perhaps the problem is how angular-router-loader webpack plugin tries to load the module.