Angular 2. Error: Loading chunk failed Angular 2. Error: Loading chunk failed typescript typescript

Angular 2. Error: Loading chunk failed


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}]})


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        });}


Here is my solution for this. I inject this service as a singleton in my app / core module.

It waits for instances of NavigationError from the router, checks if they are ChunkLoadError's and then does a redirect to the place the user wanted to go to anyway.

// Angularimport { Injectable, OnDestroy } from '@angular/core';import { Router, NavigationError } from '@angular/router';// Rxjsimport { Subscription } from 'rxjs';import { filter } from 'rxjs/operators';@Injectable()export class ChunkErrorHandler implements OnDestroy {  private subscription: Subscription;  constructor(router: Router) {    this.subscription = router.events      .pipe(filter(event => event instanceof NavigationError))      .subscribe(event => {        this.handleRouterErrors(event as NavigationError);      });  }  ngOnDestroy() {    this.subscription.unsubscribe();  }  private handleRouterErrors(event: NavigationError) {    if (event.error.name === 'ChunkLoadError') {      window.location.href = `${window.location.origin}${event.url}`;    }  }}