如何使用 Angular 路由管理 Angular 中的多篇文章?

How to manage multiple articles posts in Angular using Angular Routing?

我正在尝试使用 Angular 创建一个网站,其中有很多文章,每当我按下一篇文章时,它都会使用路由转到新的 URL。

为此,我创建了一个新的文章组件,我的 app-routing.module.ts 看起来像这样

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'about', component: AboutComponent },
  { path: 'article1', component: ArticlesComponent },
  { path: 'article2', component: ArticlesComponent },
  { path: 'article3', component: ArticlesComponent },
  { path: 'article4', component: ArticlesComponent },
  { path: 'article5', component: ArticlesComponent },
  { path: 'article6', component: ArticlesComponent },
];

我将所有内容路由到同一个组件,因为我不想为每篇文章创建一个新组件。如何根据用户对其中一篇文章的点击在该组件上显示不同的数据?

您可以为文章添加特定路径并声明路径参数(:articleId):

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'about', component: AboutComponent },
  { path: 'articles/:articleId', component: ArticlesComponent },
];

然后在您的 ArticlesComponent 中,您可以使用以下路径从路径获取当前文章 ID:

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.paramMap.pipe(
    map((params: ParamMap) => {
      const articleId = params.get('articleId')
      // fetch the article with that ID and render it
    })
  );
}

示例:访问 yourapp.com/articles/article-1 将传递 "article-1" 作为路径参数 :articleId 的值。