如何在 Angular 项目中使用类别/子类别/文章 slug 创建 SEO 友好的 URL?

Moh*_*P G -1 slug angular angular8

我正在使用 Angular 8 版本创建一个新闻应用程序。我需要显示这样的链接:www.domain.com/category/category/title 和 www.domain.com/category。我怎样才能实现这个目标?

谢谢

Kur*_*ton 5

您的字面意思是否只是指链接文本与其 href 不同的链接,如下所示

如果是这样,

<a [routerLink]="url">{{seoUrl}}</a>
Run Code Online (Sandbox Code Playgroud)

打字稿:

url: 'https://www.google.com';
seoUrl: 'https://www.google.com/category/slug';
Run Code Online (Sandbox Code Playgroud)

或者您想对页面本身的 url 执行更多操作吗?

编辑:

路由模块

// Declare two routes with an optional title. We will always redirect to the title route. Order matters here - routes will be matched in order.
{ path: 'category/:category/:title', component: CategoryComponent },
// this path declares a route similar to /category/abc where abc is a category 
{ path: 'category/:category', component: CategoryComponent }
Run Code Online (Sandbox Code Playgroud)

类别组件

// component decorator omitted for brevity
export class CategoryComponent implements OnInit {
  constructor(private route: ActivatedRoute,
    private router: Router
  ) {
  }

  ngOnInit(): void {
    // get the category from the url
    const categoryName = this.route.snapshot.paramMap.get('category');
    const titleName = this.route.snapshot.paramMap.get('title');

    // TODO: implement categoryService
    this.categoryService.getCategory(categoryName).subscribe(category => {
      if (!title) {
        this.router.navigateByUrl(`/category/${category.name}/${category.title}`);
        return;
      }

      // TODO: render the category
    });
  }
}
Run Code Online (Sandbox Code Playgroud)