首页 > 解决方案 > 错误页面重定向在角度延迟加载时无法正常工作

问题描述

我陷入了困境,需要专家的帮助。我的应用程序建立在延迟加载路由之上,所有模块都有自己的路由文件。除错误页面重定向外,一切正常。如果我点击localhost:4200/error我可以在几秒钟内看到错误页面,然后再次自动将其重定向回主页。

应用路由

const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full',
canActivate: [AuthGuardService]
},
{
path: 'home',
loadChildren: () => import('../home/home.module').then((m) => m.HomeModule),
canActivate: [AuthGuardService],
},
{
path: 'dashboard',
loadChildren: () => import('../another/another.module').then((m) => m.AnotherModule),
canActivate: [AuthGuardService],
},
{ path: '**', redirectTo: '/error' } ];

export const Routing: ModuleWithProviders = RouterModule.forRoot(routes);

错误模块:启用正常路由而不是延迟加载

const routes: Routes = [{ path: 'error', component: ErrorComponent }];

export const ErrorRoutingModule: ModuleWithProviders = RouterModule.forRoot(routes);

两个模块都像往常一样导入到 app 模块:

imports:[
  .........
  ErrorModule,
   Routing
 ]

我正在使用 Angular 8。任何帮助都会非常有帮助。

更新: 发现问题,实际上在成功登录后,我将用户从我的服务重定向到主页。

this.service.login().subscribe(response=> { if(response.valid){this.router.navigate['/home'];}

需要帮助来解决此问题。因此,也许它是一个有效用户,但在这种情况下输入了错误的 url,它应该返回error页面。此登录服务正在从我的app-component.

标签: javascriptangularangular-routingangular-router

解决方案


尝试使用此示例:

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

错误组件 ts。

export class ErrorComponent implements OnInit {
  
  public msToRelocate: number = 5000;

  constructor(private router: Router) { }

  ngOnInit() {
    Observable.of(true).pipe(
    delay(msToRelocate),
    tap(() => {
        this.goToHomePage();
      }),
    );
  }

  public goToHomePage() {
    this.router.navigate(['']);
  }

}

推荐阅读