【问题标题】:How to create SEO friendly URLs with category/subcategories/article slug in angular project?如何在 Angular 项目中创建具有类别/子类别/文章 slug 的 SEO 友好 URL?
【发布时间】:2020-05-22 15:24:06
【问题描述】:

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

谢谢

【问题讨论】:

    标签: angular angular8 slug


    【解决方案1】:

    您的字面意思是链接文本与其 href like this 不同的链接吗?

    如果是这样,

    <a [routerLink]="url">{{seoUrl}}</a>
    

    打字稿:

    url: 'https://www.google.com';
    seoUrl: 'https://www.google.com/category/slug';
    

    或者你想对页面本身的 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 }
    

    分类组件

    // 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
        });
      }
    }
    

    【讨论】:

    • 如何使用路由获取详细信息组件。我的所有新闻都将显示在同一个详细信息页面中。
    • 我将编辑我的答案。这需要更多的代码。
    • 我已经添加了一些路由来做我认为你想要的 - 它从 url 中提取类别和标题,如果它不存在则重定向到标题。我没有添加任何空值检查,您肯定希望用户输入(网址是)。
    猜你喜欢
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2015-04-04
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    相关资源
    最近更新 更多