Angular2重定向到自定义错误页面 [英] Angular2 redirect to custom error page

查看:379
本文介绍了Angular2重定向到自定义错误页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了自定义错误处理程序,因此我想重定向到我的自定义错误页面,该页面仅显示对不起,发生了错误...".

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......".

我在app-routing.module.ts文件下声明了一条路由,如下所示:

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

在此文件中,当我在error前面放置正斜杠时,它会重定向到/error url,但提示缺少404页. (它显然没有转到我的CustomErrorComponent页面).

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).

如果我从this.router.navigate(['error'])中删除了前斜杠,则它没有任何作用.

If I remove the front slash from the this.router.navigate(['error']), then it does NOTHING.

如何获取此信息以调用我在app-routing.module.ts文件中定义的CustomErrorComponent?

How do I get this to call my CustomErrorComponent I have defined in my app-routing.module.ts file?

这是CustomErrorComponent:

Here's the CustomErrorComponent:

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

export class CustomErrorComponent implements OnInit {
    constructor() { }

    ngOnInit() {
    }
}

该页面的html:

<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:当我在注释中提到它击中了我的handleError函数20次时,我并没有吐出错误...好吧,我打开了它,然后看一下现在显示(当我的this.router.navigate(['/error'])包含斜杠时会发生这种情况):

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):

未找到CustomErrorComponent的组件工厂.您是否将其添加到 @ NgModule.entryComponents

No component factory found for CustomErrorComponent. Did you add it to @NgModule.entryComponents

因此,接下来,我将其添加到我的CustomErrorComponent文件中:

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:

Component CustomErrorComponent不属于任何NgModule或 模块尚未导入到您的模块中

Component CustomErrorComponent is not part of any NgModule or the module has not been imported into your module

我尝试添加CustomErrorComponent的每个地方都失败了.我应该在哪里注册我的组件?

Every place I've tried adding the CustomErrorComponent fails. Where should I be registering my component?

推荐答案

主要问题是,来自app-routing.module.tsroutes变量在进入error之前具有进入**的条目,并且路由器将始终转到**.

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 **.

将条目**移至routes内部的最后一个位置,将使error条目可访问.

Moving the entry ** to the last place inside of routes will make the error entry reachable.

我们还发现,在更新之后,CustomErrorComponent@Component({})装饰器也已删除.

Also we found that after the updates the @Component({}) decorator of the CustomErrorComponent was removed.

让我们再次回滚,并使用以下代码保留CustomErrorComponent文件:

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

此外,我们还必须将CustomErrorComponent添加到主模块的entryComponents中.

Also we must add the CustomErrorComponent to the entryComponents of your main module.

只需将entryComponents: [CustomErrorComponent]添加到您的主模块中即可.

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重定向到自定义错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆