本文介绍了Angular2 重定向到自定义错误页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经实现了我的自定义错误处理程序,并且我想重定向到我的自定义错误页面,该页面仅显示抱歉,发生错误......".
我在 app-routing.module.ts 文件下声明了一个路由,如下所示:
import { NgModule } from '@angular/core';import { PreloadAllModules, Routes, RouterModule } from '@angular/router';从 './no-content/no-content.component' 导入 { NoContentComponent }import { CustomErrorComponent } from './customerror/customerror.component';const 路由:路由 = [{ path: '', redirectTo: '/home', pathMatch: 'full' },{ path: 'resources', loadChildren: 'app/educational-materials/educational-materials.module#EducationalMaterialsModule' },{ path: 'administrative', loadChildren: 'app/dsc/dsc.module#DSCModule' },{ 路径: '提问', loadChildren: 'app/aaq/aaq.module#AAQModule' },{ path: '**', pathMatch: 'full', component: NoContentComponent },{ 路径:'错误',组件:CustomErrorComponent }];@NgModule({进口:[RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],出口:[路由器模块],提供者:[]})导出类 AppRoutingModule { }
在我的全局异常处理程序中,我已经实现了:
import { Router } from '@angular/router';从@angular/core"导入 { ErrorHandler, Injectable, Injector };@Injectable()导出类 GlobalExceptionErrorHandler 实现 ErrorHandler {专用路由器:路由器;构造函数(注入器:注入器){setTimeout(() => this.router = injector.get(Router));}句柄错误(错误){console.log('globalExceptionHandler | handleError...');this.router.navigate(['/error']);}}
在此文件中,当我将正斜杠放在 error
前面时,它会重定向到/error url,但显示 404 页面丢失.(它显然没有转到我的 CustomErrorComponent 页面).
如果我从 this.router.navigate(['error'])
中删除前斜杠,那么它什么也不做.
如何让它调用我在 app-routing.module.ts 文件中定义的 CustomErrorComponent
?
这是自定义错误组件:
import { OnInit } from '@angular/core';导出类 CustomErrorComponent 实现 OnInit {构造函数(){}ngOnInit() {}}
以及该页面的 html:
<div class="row"><div class="col-xs-12"><h3>抱歉,处理您的请求时出错.错误已被记录.</h3>
Edit2:有没有可能是路由没有配置在正确的地方?我认为需要在根"定义路由,但它的行为就像它不存在一样(因此不会重定向).
Edit3: 当我在评论中提到它击中了我的 handleError
函数 20 次时,我并没有吐出错误......好吧,我转身看看现在显示的内容(当我的 this.router.navigate(['/error'])
包含前斜杠时会发生这种情况):
未找到 CustomErrorComponent 的组件工厂.你把它添加到@NgModule.entryComponents
接下来,我将其添加到我的 CustomErrorComponent 文件中:
import { OnInit, Component } from '@angular/core';@成分({entryComponents: [CustomErrorComponent]})导出类 CustomErrorComponent 实现 OnInit {构造函数(){}ngOnInit() {console.log('customErrorComponent | ngOnInit...');}}
现在我只需加载应用程序即可:
Component CustomErrorComponent 不是任何 NgModule 或模块尚未导入您的模块
我尝试添加 CustomErrorComponent 的每个地方都失败了.我应该在哪里注册我的组件?
解决方案
主要问题是 app-routing.module.ts
中的 routes
var 有条目**
在进入 error
之前,路由器将始终转到 **
.
将条目 **
移动到 routes
内的最后一个位置将使 error
条目可访问.
我们还发现,更新后 CustomErrorComponent
的 @Component({})
装饰器被移除了.
让我们再次回滚,并使用以下代码保留 CustomErrorComponent
文件:
import { OnInit, Component } from '@angular/core';@成分({选择器:customErrorComponent",templateUrl: './customerror.component.html'})导出类 CustomErrorComponent 实现 OnInit {构造函数(){}ngOnInit() {console.log('customErrorComponent | ngOnInit...');}}
此外,我们必须将 CustomErrorComponent
添加到主模块的 entryComponents
中.
只需将 entryComponents: [CustomErrorComponent]
添加到您的主模块.
大功告成,未来的读者可以查看问题的聊天线程以获取更多信息.
I've implemented my custom error handler, and in that I want to re-direct to my custom error page that just says "sorry, an error occurred......".
I declared a route under my app-routing.module.ts file like this:
import { NgModule } from '@angular/core';
import { PreloadAllModules, Routes, RouterModule } from '@angular/router';
import { NoContentComponent } from './no-content/no-content.component'
import { CustomErrorComponent } from './customerror/customerror.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'resources', loadChildren: 'app/educational-materials/educational-materials.module#EducationalMaterialsModule' },
{ path: 'administrative', loadChildren: 'app/dsc/dsc.module#DSCModule' },
{ path: 'ask-a-question', loadChildren: 'app/aaq/aaq.module#AAQModule' },
{ path: '**', pathMatch: 'full', component: NoContentComponent },
{ path: 'error', component: CustomErrorComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
exports: [RouterModule],
providers: []
})
export class AppRoutingModule { }
And in my global exception handler, I've implemented this:
import { Router } from '@angular/router';
import { ErrorHandler, Injectable, Injector } from '@angular/core';
@Injectable()
export class GlobalExceptionErrorHandler implements ErrorHandler {
private router: Router;
constructor(injector: Injector) {
setTimeout(() => this.router = injector.get(Router));
}
handleError(error) {
console.log('globalExceptionHandler | handleError...');
this.router.navigate(['/error']);
}
}
In this file, when I place the forward slash in front of error
, it re-directs to /error url, but says 404 page missing. (It obviously did NOT go to my CustomErrorComponent page).
If I remove the front slash from the this.router.navigate(['error'])
, then it does NOTHING.
How do I get this to call my CustomErrorComponent
I have defined in my app-routing.module.ts file?
Edit:
Here's the CustomErrorComponent:
import { OnInit } from '@angular/core';
export class CustomErrorComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
And the html for that page:
<div class="container">
<div class="row">
<div class="col-xs-12">
<h3>Sorry, an error occurred processing your request. The error has been logged.</h3>
</div>
</div>
</div>
Edit2: Is it possible that the route is not configured in the correct place? I would think the route would need to be defined "at the root", but it acts like it doesn't exist (hence not re-directing).
Edit3: When I mentioned in the comments that it was hitting my handleError
function 20 times, I wasn't spitting out the error...well, I turned that on and look what shows up now (this occurs when my this.router.navigate(['/error'])
contains the front slash):
So next, I added this to my CustomErrorComponent file:
import { OnInit, Component } from '@angular/core';
@Component({
entryComponents: [CustomErrorComponent]
})
export class CustomErrorComponent implements OnInit {
constructor() { }
ngOnInit() {
console.log('customErrorComponent | ngOnInit...');
}
}
Now I get this just loading the app:
Every place I've tried adding the CustomErrorComponent fails. Where should I be registering my component?
解决方案
Main issue is that the routes
var from the app-routing.module.ts
has the entry to **
before the entry to error
and the router will always go to **
.
Moving the entry **
to the last place inside of routes
will make the error
entry reachable.
Also we found that after the updates the @Component({})
decorator of the CustomErrorComponent
was removed.
Let's rollback that again and leave the CustomErrorComponent
file with this code:
import { OnInit, Component } from '@angular/core';
@Component({
selector: "customErrorComponent",
templateUrl: './customerror.component.html'
})
export class CustomErrorComponent implements OnInit {
constructor() { }
ngOnInit() {
console.log('customErrorComponent | ngOnInit...');
}
}
Also we must add the CustomErrorComponent
to the entryComponents
of your main module.
Just add entryComponents: [CustomErrorComponent]
to your main Module.
That did the job, future readers can check the chat thread of the question for more information.
这篇关于Angular2 重定向到自定义错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!