【问题标题】:Angular URLs (routes) customization with dynamic components使用动态组件自定义 Angular URL(路由)
【发布时间】:2021-05-26 14:01:13
【问题描述】:

我做了一个 Angular 项目(摩托车电子商务),显示产品详细信息的组件负责所有产品,因此该组件的路由始终相同:

https://fakeweb.com/second-hand-bikes/details?bikeId=7440483

这会导致所有产品都有相同的 google 链接(因为 google 忽略参数 ?bikeId=.....)

我的问题是:如何根据获取的产品自定义网址?,像这样:

https://fakeweb.com/second-hand-bikes/details/yamaha-xmax-300

我想过编写一个脚本,每次在后端添加新产品时手动创建路由,但看起来很痛苦。

有什么想法吗?感谢您提供任何类型的帮助!

【问题讨论】:

  • 为什么不在路线中使用你的bikeId?

标签: angular firebase routes seo server-side-rendering


【解决方案1】:

显示特定产品详细信息的组件的路由需要该产品名称的路由参数。我们可以使用以下路由来实现:

export const routes: Routes = [
  [...]
  { path: 'second-hand-bikes/details/:name', component: ProductDetails }
];

ProductDetails 组件必须读取参数,然后根据参数中给出的名称加载产品。 ActivatedRoute 服务提供了一个参数Observable,我们可以订阅它来获取路由参数:

productName: string;
private sub: any;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.sub = this.route.params.subscribe(params => {
     this.productName = params['name'];

     // In a real app: dispatch action to load the details here.
  });
}

ngOnDestroy() {
  this.sub.unsubscribe();
}

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多