如何在 Angular 程序中将未知路由重定向到主路由?

How to redirect unknown routes to home route in Angular program?

我有一个 routes.ts 文件,如下所示:

import { AuthGuardService as AuthGuard } from '../services/auth-guard.service';

export const routes:Routes = [
    {path : '' , redirectTo : '/home' , pathMatch : 'full'},
    {path: 'home' , component : HomeComponent},
    {path: 'users' , component : UsersComponent, canActivate: [AuthGuard]},

];

还有一个像这样的 auth-guard.service.ts 文件:

export class AuthGuardService implements CanActivate {

  constructor(public auth: AuthService, public router: Router) {}
  canActivate(): boolean {
    if (!this.auth.isLoggedIn()) {
      this.router.navigate(['home']);
      return false;
    }
    return true;
  }
}

它适用于像 users 这样的已知路线,但是当我尝试像 homeee 这样的未知路线时,它不能正常工作,并显示一个带有页眉和页脚但没有内容的页面。如何将所有未知路由重定向到主组件?

另外我想知道这是不是我喜欢做的事情的好方法? (我喜欢只有登录的用户才能访问除主页组件之外的其他组件以及登录前的所有路由都被重定向到主页组件)。

Angular 文档建议定义一个 wildcard route

Add a wildcard route to intercept invalid URLs and handle them gracefully. A wildcard route has a path consisting of two asterisks. It matches every URL. The router will select this route if it can't match a route earlier in the configuration. A wildcard route can navigate to a custom "404 Not Found" component or redirect to an existing

The router selects the route with a first match wins strategy. Wildcard routes are the least specific routes in the route configuration. Be sure it is the last route in the configuration.

你的情况:

{ path: '**', redirectTo: 'home'}

通过添加后备路线增强您现有的路线阵列:

export const routes:Routes = [
    {path : '' , redirectTo : '/home' , pathMatch : 'full'},
    {path: 'home' , component : HomeComponent},
    {path: 'users' , component : UsersComponent, canActivate: [AuthGuard]},
    {path: '**' , component : HomeComponent},

];

小心将它包含在数组的末尾,否则它会捕获所有路由。