重定向错误404 Angular 5

时间:2017-12-05 13:55:09

标签: angular http-status-code-404

我正在尝试在网址错误时处理404错误http://localhost:8100/#/login。这是我的登录URL,如果我写了像http:... / loginasdasd这样的东西,我想自动打开我自己的NotFoundPage。

const appRoutes3: Routes = [
  {
    path: '',
    children: [
      {
         path: 'login',
         component: LoginPage
      },
      { path: 'login**', redirectTo: '/notfound' }
   ]
 },
 { path: 'notfound', component: NotFoundPage }
];


RouterModule.forRoot(
  appRoutes3,
  { enableTracing: true } // <-- debugging purposes only
)
,
IonicModule.forRoot(MyApp, {}, {
  links: [
    { component: HomePage, name: "Home", segment: "" },
    { component: LoginPage, name: "Login", segment: "login", defaultHistory: [HomePage] },
    { component: SubscribePage, name: "Signup", segment: "signup", defaultHistory: [HomePage] },
    { component: SubscribeExtendPage, name: "Signup", segment: "signup-extend", defaultHistory: [HomePage] },
    { component: MainPage, name: "Main", segment: "main", defaultHistory: [HomePage] },
    { component: WelcomePage, name: "Welcome", segment: "welcome" },
    { component: NotFoundPage, name: "notFound", segment: "login/**", defaultHistory: [HomePage] },
  ]
}
)
],

我是一个有角度的菜鸟,我不知道如何正确地做到这一点,我发现的最好的信息是https://vsavkin.com/angular-router-understanding-redirects-2826177761fc在其他一些角度重定向帖子中。

请一些帮助或任何线索将不胜感激。 感谢。

3 个答案:

答案 0 :(得分:4)

您需要使用狂野角色(**)。 **路径应该是最后路线。如果请求的URL与配置中定义的路由的任何路径不匹配,路由器将选择此路由。这对于显示&#34; 404 - Not Found&#34;页面或重定向到另一条路线。

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
   path: 'heroes',
   component: HeroListComponent,
 data: { title: 'Heroes List' }
 },
 {  path: '',
 redirectTo: '/heroes',
 pathMatch: 'full'
 },
 { path: '**', component: PageNotFoundComponent }
];

希望这有帮助。

答案 1 :(得分:1)

当Angular尝试按照您在Routes数组中声明的顺序匹配路由时。你可以这样做:

const appRoutes3: Routes = [
  {
    path: '',
    children: [
      {
         path: 'login',
         component: LoginPage
      }
 },
 { path: '**', component: NotFoundPage }
];

但如果你真的想要一条路线/notfound,请更改redirectTo: '/notfound'的{​​{1}}。

答案 2 :(得分:0)

下面的代码在我的情况下可以正常工作

{ path: '404', component: PageNotFoundComponent }

在您的app.component.ts中添加以下代码

constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        let routerError = error.toString();
        if (routerError.indexOf('Cannot match any routes') >= 0 ) {
           this.router.navigate(['/404']);
        } else {
           throw error;
        }
    }
  }