在 Angular 中使用 RouterLink 激活路由

发布日期:2026-07-09 05:17:05   来源 : 杭州电子商务研究院    浏览量 :2
杭州电子商务研究院 发布日期:2026-07-09 05:17:05  
2

介绍

当用户在 Web 应用中执行任务时,Angular 中的路由可帮助从一个视图导航到另一个视图。在本指南中,您将了解 Angular 路由器的主要功能 RouterLink 以及如何在 Angular 应用中使用routerLink 。

角度路由

您可以将应用程序的路由配置为对象数组,并将它们传递给 Angular 的RouterModule.forRoot

文件名:app.routes.ts

      import { RouteModule, Routes } from '@angular/router';

const routes: Routes = [
    { path: 'component-one', cmponent: ComponentOne }, { path: 'component-two', cmponent: ComponentTwo }
];
export const routing = RouterModule.forRoot(routes);
    

然后,在应用程序的根目录中导入路由配置。

      import { routing } from './app.routes';
@NgModule({
   imports: [ BrowserModule, routing],
   declarations: [
      AppComponent,
      ComponentOne,
      ComponentTwo
   ],
   bootstrap: [ AppComponent ]
})
export class AppModule {}
    

默认情况下,应用会导航至空路线。您可以将其重定向至其中一条命名路线。

文件名:app.routes.ts

      {path: '', redirectTo: 'component-one', pathMatch: 'full'}
    

pathMatch属性是重定向所必需的,它告诉路由应如何匹配提供的 URL 才能重定向到指定的路由。由于提供了pathMatch : full ,如果整个 URL 与空path('')匹配,则路由将重定向到component-one

在 HTML 中链接路线

要向其中一条路由添加链接,请在 HTML 中使用routerLink指令。此指令接受一个数组。第一个参数是路由的名称,第二个参数是要随路由传递的参数。

      <a [routerLink]="['component-one', routeParams]"></a>
    

如果使用不带括号的routerLink指令,则需要将路由作为字符串传递。

      <a routerLink="/component-one"></a>
    

您还可以在 Angular 中以编程方式更改路线。

      this.router.naigate(['/component-one']);
    

<router-outlet> </router-outlet>充当组件的占位符。Angular 会动态地将要激活的路由的组件添加到其中。

在 Angular 中访问路由参数

路由器提供了两种不同的方法来获取路由参数。它们是:

快照

ActivatedRoute服务提供当前路线的快照。

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

@Component({
     ...
})
export class SampleComponent implements OnInit {
     constructor(private route : ActivatedRoute) {}

ngOnInit() {
    this.myParam = this.route.snapshot.params.myParam;
}
}
    

这很简单,也足够了。但是由于 Angular 重用了组件以提高性能,因此在某些情况下此方法不起作用,例如,如果您从/product/1/product/2导航。在这种情况下,您需要使用 Observable/Stream 方法。

可观察/流

此方法使用可观察对象,当您从一个路由导航到另一个路由时,可观察对象将传递新数据。Angular v4+ 路由器提供了ParamMap,这是一个您可以使用的可观察对象。

      ngOnInit() {
  // subscribe to the parameters observable
  this.route.paramMap.subscribe(params => {
    console.log(param.get('myParam'));
    this.myParam = params.get('myParam');
  })
}
    

如果您使用的是 v4 之前的 Angular 版本,则可以使用params而不是paramMap获取路由参数。

      ngOnInit() {
  // subscribe to the parameters observable
  this.route.params.subscribe(params => {
    console.log(params.get('myParam'));
    this.myParam = params.get('myParam');
  });
}

## Using a Child Route in Angular

While some routes may only be accessible and viewed within other routes, it may be appropriate to create them as child routes, for example, if you have a product route with an individual ID and want to navigate to other routes to see its overview or specification.

The children property in the routes accepts an array of child routes. You can use the same <router-outlet> directive to hold the child component.

File name: `app.routes.ts`
```typescript
export const routes: Routes = [
{ path: 'product-details/:id', component: ProductDetails,
    children: [
       { path: '', redirectTo: 'overview', pathMatch: 'full',
       { path: 'overview', component: Overview },
       { path: 'specification', component: Specification }
     ]
  }
}
    

查询和路由参数

查询参数和路由参数之间的主要区别在于,路由参数对于确定路由至关重要,而查询参数是可选的。可选参数等于/product-list?page=2 ,而路由参数为/product-list/2

      // Pass query params in router link
<a [routerLink]="['product-list']" [queryParams]="{ page: 2 }"> Go to Page 2</a>

// query parameters programmatically
this.router.navigate(['/product-list'], {  queryParams: {  page: pageNum } });
    

要读取查询参数,请订阅ActivatedRoute中的queryParams

      ngOnInit() {
  this.sub = this.route.queryParams.subscribe(params => {
      this.page = +params['page'] || 0;
  });
}
    

结论

在本指南中,我们探讨了如何使用routerLink在 Angular 中激活路由。我们还了解了如何在 HTML 中链接路由、使用子参数访问参数以及查询参数和路由参数之间的区别。

您可以在我的指南《理解 Angular 中路由的目的》中了解有关 Angular 的更多信息。

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