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

Ayu*_*aik 1 typescript angular angular-router

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

1

为此,我创建了一个新的文章组件,我的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 },
];
Run Code Online (Sandbox Code Playgroud)

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

Tsv*_*nev 5

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

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'about', component: AboutComponent },
  { path: 'articles/:articleId', component: ArticlesComponent },
];
Run Code Online (Sandbox Code Playgroud)

然后,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
    })
  );
}
Run Code Online (Sandbox Code Playgroud)

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