angular - 如何在斯巴达克斯中抑制静态页面的自定义上下文?

标签 angular sap-commerce-cloud spartacus-storefront

我们有static pages configured在我们的 Spartacus 项目中,Spartacus 还配置了自定义站点上下文。假设 SiteContext 的自定义参数为 custom,URL 为 www.storefront.com/custom。那么内容页面也将位于自定义参数之后。我们可以抑制它并仅使用 www.storefront.com/staticPage 而不是 www.storefront.com/custom/staticPage 吗?

最佳答案

是的,您可以将某些路由排除在其前面添加站点上下文之外。

斯巴达克斯provides定制Angular UrlSerializer - SiteContexturlSerializer 。它负责在实际 URL 路径之前添加站点上下文 URL 段。

因此,您应该扩展斯巴达克斯的序列化程序并提供您的自定义版本,在某些情况下,该版本不会前置站点上下文。例如在您的 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 === '/staticPage';
  }
}

注意:此解决方案适用于任何 URL 排除。它们不必是静态的 Angular 路由。

关于angular - 如何在斯巴达克斯中抑制静态页面的自定义上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74026451/

相关文章:

javascript - 来自另一个类的 Angular 4 设置属性

javascript - 改变 ionic 清新器的位置

enums - hybrisFlexiblesearch - 带枚举的 where 子句

azure - SAP Commerce Cloud 热文件夹本地设置

angular - 如何在 Spartacus 2.1 中使用类型增强?

具有多个项目和库的 Angular 构建过程

css - 在禁用的输入上更改自定义输入范围缩略图背景颜色

java - 如何实例化封装对象?

spartacus-storefront - 适用于多种环境的 Spartacus CCv2 构建过程

java - 斯巴达克斯中的 SmartEdit 设置