【问题标题】:How to suppress custom context for static pages in Spartacus?如何抑制 Spartacus 中静态页面的自定义上下文?
【发布时间】:2022-10-19 19:03:28
【问题描述】:
我们的 Spartacus 项目中有 static pages configured,并且 Spartacus 还配置了自定义站点上下文。比如说,SiteContext 的自定义参数是custom,URL 是www.storefront.com/custom。然后内容页面也将在自定义参数之后。我们可以压制它并只使用www.storefront.com/staticPage 而不是www.storefront.com/custom/staticPage 吗?
【问题讨论】:
标签:
angular
sap-commerce-cloud
spartacus-storefront
【解决方案1】:
是的,您可以将某些路由排除在附加站点上下文之前。
斯巴达克斯provides 自定义Angular UrlSerializer - SiteContexturlSerializer。它负责在实际 URL 路径之前添加站点上下文 URL 段。
因此,您应该扩展 Spartacus 的序列化程序并提供您的自定义版本,在某些情况下不会预先添加站点上下文。例如在您的 app.module 中提供它:
providers: [
{ provide: UrlSerializer, useExisting: CustomSiteContextUrlSerializer },
]
这是示例实现:
@Injectable({ providedIn: 'root' })
export class CustomSiteContextUrlSerializer extends SiteContextUrlSerializer {
/**
* Default Angular implementation of the `serialize` method.
* * Calling simply `super.serialize()` is not what we want - it would
* execute the method of the direct parent class - Spartacus' `SiteContextUrlSerializer`.
* To access the implementation of the super-super class, we derive it
* directly from the prototype of `DefaultUrlSerializer`.
*/
defaultSerialize = DefaultUrlSerializer.prototype.serialize.bind(this);
serialize(tree: UrlTreeWithSiteContext): string {
const url = this.defaultSerialize(tree);
if (this.shouldExcludeContext(url)) {
return url; // simply serialized URL (without context)
} else {
return super.serialize(tree); // delegate serialization to `SiteContextUrlSerializer`
}
}
// I'm not sure this is really needed, but it's here for completeness:
parse(url: string): UrlTreeWithSiteContext {
const urlTree = super.parse(url);
if (this.shouldExcludeContext(url)) {
urlTree.siteContext = {}; // clear context metadata
}
return urlTree;
}
/**
* Your custom rule for recognizing URLs that should not
* have the context prepended.
* For example: `/cart` and `/staticPage`.
*/
protected shouldExcludeContext(url: string): boolean {
return url === '/cart' || url === '/spike';
}
}
注意:此解决方案适用于任何 URL 排除项。它们不必是静态的 Angular 路由。