Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2. Error: Loading chunk failed

Using angular 2 with lazy loaded modules, I can receive(for example) 401 HTTP code from server

bootstrap 0b40fee…:101 GET http://localhost:8082/2.chunk.js

Error: Loading chunk 2 failed.
at HTMLScriptElement.onScriptComplete (bootstrap 0b40fee…:91)
at HTMLScriptElement.wrapFn (zone.js:1032)
at ZoneDelegate.invokeTask (zone.js:414)
at Object.onInvokeTask (core.es5.js:4119)
at ZoneDelegate.invokeTask (zone.js:413)
at Zone.runTask (zone.js:181)
at HTMLScriptElement.ZoneTask.invoke (zone.js:476)

How to handle this error?

like image 452
smie Avatar asked May 17 '17 20:05

smie


2 Answers

Check my answer for details

  • Workaround to bypass this chunk fails error => Programmatically force app to reload if chunks failed error occurs using global error handler.

import { ErrorHandler } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  handleError(error: any): void {
   const chunkFailedMessage = /Loading chunk [\d]+ failed/;

    if (chunkFailedMessage.test(err.message)) {
      window.location.reload();
    }
  }
}
  • Provide it in our root module to change default behavior in our app, so instead of using default ErrorHandler class we are using our custom GlobalErrorHandler class.

@NgModule({   
  providers: [{provide: ErrorHandler, useClass: GlobalErrorHandler}]
})
like image 121
Khaled Lela Avatar answered Sep 30 '22 13:09

Khaled Lela


I was having the same problem so I investigated. I found the solution. This happened to me when I redeployed to another server and the chunk had a [hash].

You can catch the error either in a catch all like this:

ngOnInit() {
    if (!this.previousRouterErrorHandler) {
        this.previousRouterErrorHandler = this.router.errorHandler;
        let that = this;
        this.router.errorHandler = function (err: any) {
            // Handle here. err.message == "Loading chunk chunk-name failed."

            return that.previousRouterErrorHandler.apply(that.previousRouterErrorHandler, arguments);
        };
    }
}

Or directly at the link which navigated

click() {
    this.router.navigate(['/lazy-route'])
        .catch(err => {
            // Handle here
        });
}
like image 25
jsgoupil Avatar answered Sep 30 '22 13:09

jsgoupil