前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SAP Spartacus的自定义Angular Url Matcher实现

SAP Spartacus的自定义Angular Url Matcher实现

作者头像
Jerry Wang
发布2020-12-17 14:30:24
6420
发布2020-12-17 14:30:24
举报

https://microlearning.opensap.com/media/Custom+Angular+URL+Matchers+in+Spartacus+Storefront±+SAP+Commerce+Cloud/1_hhjqkiuy/178316081

Angular, and Spartacus by extension, allows you to configure string patterns to match routes against URLs. An example is /product/:productCode, which has two segments. The first segment, product, is a static segment that determines the URL is a product page type, and the second segment, :productCode, is a dynamic parameter.

上面提到的url,有两个segments,其中第一个product segment,为静态segment,说明该url代表一个product page type,而第二个segment :productCode, 是一个动态参数。

有时存在需求,需要在一个segment内同时实现静态和动态两种segment:

However, there may be cases where you need to work with URL segments that contain both static and dynamic parts within a single segment. An example is /macbook-p, where mackbook is a dynamic product code, and -p is a static part that determines the URL is a product page type. In this case, you need to implement a custom Angular UrlMatcher.

这种需求通过UrlMatcher来满足。

源代码:

代码语言:javascript
复制
/**
 * Matches pattern `/:productCode-p`
 * @param segments
 */
export function customProductUrlMatcher(
  segments: UrlSegment[]
): UrlMatchResult | null {
  // check if URL ends with `-p`
  if (segments.length === 1 && segments[0].path.endsWith('-p')) {
    // Remove last two characters (which are `-p`), and treat the rest as a product code
    const productCode = segments[0].path.slice(0, -2);
    return {
      consumed: segments,
      posParams: { productCode: new UrlSegment(productCode, {}) },
    };
  }
  return null;
}

将自定义实现的matcher配置到module里:

代码语言:javascript
复制
ConfigModule.withConfig({
  routing: {
    routes: {
      product: {
        matchers: [customProductUrlMatcher],
        paths: [':customProductCode'],
      },
    },
  },
}),

上面代码中paths里传入的:customProductCode是一个新的属性,需要通过normalizer添加进去:

代码语言:javascript
复制
@Injectable()
export class CustomProductNormalizer
  implements Converter<Occ.Product, Product> {
  convert(source: Occ.Product, target?: Product): Product {
    target['customProductCode'] = source.code + '-p';
    return target;
  }
}

最后将custom normalizer注入到app module中:

代码语言:javascript
复制
providers: [
  {
    provide: PRODUCT_NORMALIZER,
    useClass: CustomProductNormalizer,
    multi: true,
  },
],
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-12-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档