在 Angular 中从代码导航到路由

发布日期:2026-07-10 00:02:04   来源 : 杭州电子商务研究院    浏览量 :2
杭州电子商务研究院 发布日期:2026-07-10 00:02:04  
2

介绍

大家好!如您所知,Angular 是一个单页应用程序,它没有多页 HTML 页面来创建不同的路由,因此我们需要一个客户端路由解决方案。Angular Router 帮助我们通过几个简单的步骤创建客户端路由,然后我们可以使用routerLink进行渲染。今天,我将向您介绍使用代码从组件导航到其他各种组件的不同选项,以便您可以使用不同的条件动态导航用户。

我们将涵盖的内容

  • 动态路由的必要性
  • 使用不同的组件制作路线
  • 使用代码中的路由在组件之间导航

动态路由的需求

让我们举一个现实生活中简单的例子。假设您的应用程序中有多个角色,并且根据角色,您必须决定用户是否有权访问您的应用程序。如果他们有权限,您将把他们导航到应用程序的主页;否则,您将把他们带到不同的页面,最好使用 403 状态代码。

在这种情况下,您需要在登录页面提交表单时一次性决定路由。那么您要怎么做呢?

这里就需要用到动态路由。首先,您将检查条件,然后根据条件动态决定将用户发送到的路由。

让我们通过在app-routing.module.ts中创建路由来开始下一部分

使用不同的组件创建路线

现在我们将制作一些组件,以帮助我们更清楚地理解 Angular Router。我将分别创建三个组件:FirstComponentSecondComponentFirstChildComponentFirstChildComponent将在FirstComponent中用作子组件。

以下命令将创建组件。

      ng g c first --skipTests=true
ng g c second --skipTests=true
ng g c first-child --skipTests=true
    

我们已经成功创建了组件;现在,我们将用不同的 URI 映射它。成功配置app-routing.module.ts后,它将如下所示。

      import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SecondComponent } from './second/second.component';
import { FirstComponent } from './first/first.component';
import { FirstChildComponent } from './first-child/first-child.component';

const routes: Routes = [
  {
    path: 'first',
    component: FirstComponent,
    children: [
      {
        path: 'first-child',
        component: FirstChildComponent
      }
    ]
  },
  {
    path: 'second',
    component: SecondComponent
  },
  {
    path: "",
    redirectTo: '/first',
    pathMatch: 'full'
  }
];

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

在路由文件中,我们创建了两个主要路由,/first/second,以及一个重定向到/first 的默认路由。它主要用于最初将用户重定向到主页。我们还创建了子路由来解释父子关系的动态导航。

现在是时候编写使用路由在组件之间导航的代码块了。

我现在不打算写条件;相反,我会在app.component.html中创建几个按钮。单击时,它将导航到不同的组件。

      <div>
    <button type="button" class="btn" (click)="navigateToFirst()">First</button>
    <button type="button" class="btn" (click)="navigateToSecond()">Second</button>
</div>

<router-outlet></router-outlet>
    

如您所见,我们已成功在app.component.html中添加了两个按钮,并且单击事件方法将分别调用navigationToFirst()navigationToSecond()。这些方法将调用Router类的navigation()方法导航到另一个视图。

所以让我们将这些功能添加到我们的app.component.ts文件中。

      import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(private _router: Router) { }

  navigateToFirst() {
    this._router.navigate(['first'])
  }
  navigateToSecond() {
    this.router.navigateByUrl('/second')
  }

}
    

这里我们在构造函数中注入了路由器类,使我们能够从一个视图导航到另一个视图。它有两种方法,navigatenavigationByUrl,用于导航路线。它们很相似;唯一的区别是,navigate方法采用连接在一起并用作 URL 的数组,而navigationByUrl方法采用绝对路径。

例如,如果我们必须导航到/students/1,我们可以通过两种方式导航到该 URL。

  1. this._router.navigate(['学生',1])
  2. this._router.navigateByUrl('/students/1')

单击按钮时,您可以添加一些条件来根据不同的条件引导用户。

现在我要应用一些 CSS 来美化我们的应用程序。我会将其放在style.scss文件中。

      .btn{
    color: white;
    background-color: blue;
    border: none;
    padding: .5em 2em;
    border-radius: 2em;
    box-shadow: 0 0 2px 2px;
    font-size: 18px;
    margin-left: 5px;
    margin-right: 5px;
    outline: none;
    &:hover{
        background-color: gray;
        cursor: pointer;
    }
}
    

我在这里使用了 SCSS。如果您不熟悉它,可以在此处阅读。如果您不熟悉 SCSS,也可以使用 CSS。

我们的输出将会像这样。

现在是时候将FirstChildComponent引入画面了。我们将在first.component.html中创建一个类似app.component.html的按钮。

      <p>first works!</p>
<button type="button" class="btn" (click)="navigateToFirstChild()">First</button>
<router-outlet></router-outlet>
    

在first.component.ts中进行更改后,它将看起来像上面的代码片段,其中我们有一个按钮,它将在点击事件上调用一个函数,然后导航它并显示子视图。

现在我们将在first.component.ts中创建一个函数来导航到FirstChildComponent

      import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.scss']
})
export class FirstComponent implements OnInit {

  constructor(
    private _router: Router,
    private _activatedRoute:ActivatedRoute
    ) { }

  navigateToFirstChild() {
    this._router.navigate(["first-child"],{relativeTo:this._activatedRoute})
  }

}
    

注意:navigation()方法中,我传递了一个额外的参数。它是一种称为NavigateExtras的对象。我们使用了NavigateExtrasrelatedTo,并在值中给出了ActivatedRoute的实例。因此,您无需在数组中提供整个 URL,它会自动在现有 URL 后扩展当前参数。

最后,我们的输出看起来像这样。

结论

希望您喜欢本指南。在多种情况下您可能需要动态路由。我在上面的例子中解释了其中一些。我试图涵盖动态导航的所有方面。要学习更有效地使用动态路由,请在此处阅读更多相关信息。

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据