typescript Angular 2. 错误:加载块失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44034039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2. Error: Loading chunk failed
提问by smie
Using angular 2 with lazy loaded modules, I can receive(for example) 401 HTTP code from server
使用带有延迟加载模块的 angular 2,我可以从服务器接收(例如)401 HTTP 代码
bootstrap 0b40fee…:101 GET http://localhost:8082/2.chunk.js
引导程序 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?
如何处理这个错误?
回答by Khaled Lela
Check my answerfor details
详情请查看我的回答
- Workaround to bypass this chunk fails error => Programmatically force app to reload if chunks failed error occurs using
global error handler
.
- 绕过此块失败错误的解决方法 => 如果使用
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.
- 在我们的根模块中提供它以更改我们应用程序中的默认行为,因此我们使用我们的自定义
GlobalErrorHandler
类而不是使用默认的 ErrorHandler类。
@NgModule({
providers: [{provide: ErrorHandler, useClass: GlobalErrorHandler}]
})
回答by jsgoupil
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].
我遇到了同样的问题,所以我进行了调查。我找到了解决方案。当我重新部署到另一台服务器并且块有 [hash] 时,这发生在我身上。
You can catch the error either in a catch all like this:
您可以在 catch all 中捕获错误,如下所示:
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
});
}
回答by vijayliebe
It happen when when deploy new code.The manifest.js
which holds the files and hashes doesn't update without refreshing and when it loads a chunk it obviously uses the old hash from manifest.js.
当部署新代码时会发生这种情况。manifest.js
保存文件和散列的文件在不刷新的情况下不会更新,并且当它加载一个块时,它显然使用来自 manifest.js 的旧散列。
So while catching error we can do force reload with given url :-
因此,在捕获错误时,我们可以使用给定的 url 强制重新加载:-
click() {
this.router.navigate(['/lazy-route'])
.catch(err => {
// Handle here
// reload with given route
// window.location.pathname('/lazy-route');
// OR
// reset existing route(containing query params) with given route and force reload
window.history.pushState({}, document.title, '/lazy-route' );
window.location.reload();
});
}
回答by Eredian
chunk related errors can be raised by any environment or routing related issues making them hard to debunk.
任何环境或路由相关问题都可能引发与块相关的错误,这使得它们难以揭穿。
In my case, the amount of data moving in my PWA was too much to handle by the angular router. It was flooding the headers of the js chunks getters and therefore raising bad_request errors.
就我而言,我的 PWA 中移动的数据量太多,无法由 angular 路由器处理。它淹没了 js 块 getter 的标头,因此引发了 bad_request 错误。
I suggest you to check out those network calls (getters of chunks.js like http://localhost:xxxx/158.js) for anything unusual in headers and refactor sketchy stuff in your current dev environment, since it's a real black hole time to investigate the source of the error by yourself.
我建议您检查那些网络调用(chunks.js 的 getter,如http://localhost:xxxx/158.js)以了解标头中的任何异常,并在您当前的开发环境中重构粗略的东西,因为这是一个真正的黑洞时间自行调查错误的来源。
Hope that'll help
希望这会有所帮助
回答by christo8989
In my case, I was putting my files in an S3 bucket. I kept getting this error because it was calling the wrong filenames all together and returning an html error response.
就我而言,我将文件放在 S3 存储桶中。我不断收到此错误,因为它同时调用了错误的文件名并返回了 html 错误响应。
At some point I let the IT team know what was happening. They were like, let's invalidate the cache on CloudFront... What?! Yeah! Let's do that...
在某些时候,我让 IT 团队知道发生了什么。他们就像,让我们使 CloudFront 上的缓存无效......什么?!是的!让我们这样做...
Moral of the story, if you've been searching the web for answers to this error and can't find any, check with the IT team or any place that the index.html file might be getting cached.
这个故事的寓意是,如果您一直在网上搜索此错误的答案但找不到答案,请与 IT 团队或任何可能缓存 index.html 文件的地方联系。
回答by Questioning
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.
它等待来自路由器的 NavigationError 实例,检查它们是否是ChunkLoadError
's 然后重定向到用户无论如何都想去的地方。
// Angular
import { Injectable, OnDestroy } from '@angular/core';
import { Router, NavigationError } from '@angular/router';
// Rxjs
import { 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}`;
}
}
}
回答by dee zg
this probably means unhandled exception. you have to handle error responses (4xx, 5xx status codes) from server in whatever way you want: show error message somewhere, redirect to some page, do anything but not leave it unhandled.
这可能意味着未处理的异常。您必须以任何您想要的方式处理来自服务器的错误响应(4xx、5xx 状态代码):在某处显示错误消息、重定向到某个页面、执行任何操作但不要对其进行处理。
for example:
例如:
return this.http.get(requestDetails)
.map(res => res.json())
.catch(err => {
console.log('server error:', err)
Observable.throw(err);
});