当路由参数和地址无效时,Angular 2不会重定向到404页面

时间:2017-05-17 15:28:51

标签: javascript c# angular typescript asp.net-core

我正在使用Angular 4.1.1开发一个应用程序。 我总是在模块中声明路由,我在 所有模块中执行此操作。

例如,new-cars.routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { NewCarsComponent} from './new-cars.component';
import { NewCarsResolver } from './new-cars.resolver';    

@NgModule({
    imports: [
        RouterModule.forChild([
            {
                path: 'cars/:id',
                component: NewCarsComponent,
                resolve: {
                    card: NewCarsResolver
                }
            }
        ])
    ],
    exports: [RouterModule]
})

export class NewCarsRoutingModule { }

我在app-routing.module.ts中为不正确的路线声明了这条路线:

export const routes: Routes = [
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true})],
  exports: [RouterModule]
})

export class AppRoutingModule {}

如果我以这种格式写下面的地址,它会正确处理错误的地址:

http://foowebsite/#/sdf /*the address exists*/

但是,以下地址是错误的,它们只是重定向到主页,但我想显示404 page

http://foowebsite/#/news/-5  /*There is no such route param "-5".Redirecting to home page, but I want to show 404 error*/

http://foowebsite/sdf  /*There is no "sdf" component/module routing. Redirecting to home 
page, but I want to show 404 error*/

我尝试过的事情:

export const routes: Routes = [  
  { path: '404', component: PageNotFoundComponent },
  { path: '**', component: PageNotFoundComponent }
];

export const routes: Routes = [  
  { path: '404', component: PageNotFoundComponent },
  { path: '**', redirectTo: '/404' }
];

但是,无效的网址只会被重定向到主页。请注意,我使用模块路由在模块和应用程序路由中路由以重定向到404页面。

我的app.module.ts文件:

import { AppRoutingModule } from './app-routing.module';

@NgModule({
    imports: [
        ...
        AppRoutingModule        
    ],
    declarations: [
        AppComponent,
        PageNotFoundComponent
        ],
    bootstrap: [AppComponent]
})
export class AppModule { }

我的{1}} ASP.NET核心Web应用程序如下所示:

web.config

即使我故意返回<system.webServer> <httpErrors> <remove statusCode="500" subStatusCode="-1" /> <remove statusCode="404" subStatusCode="-1" /> <error statusCode="404" prefixLanguageFilePath="" path="/404" responseMode="ExecuteURL" /> <error statusCode="500" prefixLanguageFilePath="" path="/404" responseMode="ExecuteURL" /> <error statusCode="500" subStatusCode="100" path="/404" responseMode="ExecuteURL" /> </httpErrors> </system.webServer> 错误,也不会出现错误页面:

404

我应该写什么来重定向到404页面?

1 个答案:

答案 0 :(得分:0)

试试这个:

{path: '404', component: PageNotFoundComponent },
{path: '**', redirectTo: '/404'}