Angular Routing 是 Angular 框架中用于页面导航和组件间通信的重要机制。它允许开发者定义路由规则,从而实现单页面应用(SPA)的流畅导航。

路由配置

在 Angular 中,路由配置通常在 app-routing.module.ts 文件中进行。以下是一个简单的路由配置示例:

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

路由守卫

路由守卫是 Angular 中用于控制路由访问权限的一种机制。它可以在路由导航之前执行一些逻辑,例如检查用户是否已登录。

以下是一个简单的路由守卫示例:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    // 检查用户是否已登录
    return this.authService.isAuthenticated();
  }
}

动态路由参数

动态路由参数允许你根据 URL 中的参数动态地渲染组件。

以下是一个包含动态路由参数的路由配置示例:

const routes: Routes = [
  { path: 'user/:id', component: UserComponent }
];

在这个例子中,:id 是一个动态路由参数,它会在组件中通过 ActivatedRoute 服务获取。

Angular Routing Diagram

更多信息,请访问我们的 Angular 教程 页面。

Angular Routing 是 Angular 框架中用于页面导航和组件间通信的重要机制。它允许开发者定义路由规则,从而实现单页面应用(SPA)的流畅导航。

### 路由配置

在 Angular 中,路由配置通常在 `app-routing.module.ts` 文件中进行。以下是一个简单的路由配置示例:

```typescript
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

路由守卫

路由守卫是 Angular 中用于控制路由访问权限的一种机制。它可以在路由导航之前执行一些逻辑,例如检查用户是否已登录。

以下是一个简单的路由守卫示例:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    // 检查用户是否已登录
    return this.authService.isAuthenticated();
  }
}

动态路由参数

动态路由参数允许你根据 URL 中的参数动态地渲染组件。

以下是一个包含动态路由参数的路由配置示例:

const routes: Routes = [
  { path: 'user/:id', component: UserComponent }
];

在这个例子中,:id 是一个动态路由参数,它会在组件中通过 ActivatedRoute 服务获取。

Angular Routing Diagram

更多信息,请访问我们的 Angular 教程 页面。