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来满足。
源代码:
/**
* 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里:
ConfigModule.withConfig({
routing: {
routes: {
product: {
matchers: [customProductUrlMatcher],
paths: [':customProductCode'],
},
},
},
}),
上面代码中paths里传入的:customProductCode是一个新的属性,需要通过normalizer添加进去:
@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中:
providers: [
{
provide: PRODUCT_NORMALIZER,
useClass: CustomProductNormalizer,
multi: true,
},
],