如何在Spartacus中新增自定义OccEndpoint并配置关联自定义页面接口
Spartacus 自定义页面配置OccEndpoint实现标准化返回操作步骤
1. 扩展OccEndpoints类型定义(避免TypeScript类型报错)
在项目的全局类型声明文件(如occ-extension.d.ts或src/typings.d.ts)中添加自定义端点的类型声明:
declare module '@spartacus/core' { interface OccEndpoints { // 替换为你自定义页面的端点标识,和后续配置保持一致 customPage?: string; } }
2. 注册端点与字段层级映射
在根模块的配置提供项(或单独的Spartacus配置模块)中,参照PLP的配置规则添加对应配置,确保字段处理逻辑和PLP完全对齐:
import { provideConfig, OccConfig } from '@spartacus/core'; @NgModule({ providers: [ provideConfig({ backend: { occ: { endpoints: { // 替换为后端自定义Controller对应的接口路径,占位符和你实际传参匹配 customPage: 'custom/pages/${pageCode}?fields=${fields}', }, // 和你之前配置的fieldSetLevelMapping规则对齐,参照PLP的字段层级定义 fieldSetLevelMapping: { customPage: { LIST: 'basic', FULL: 'FULL', // 按需添加你需要的字段层级,和PLP配置规则保持一致 } } } } } as OccConfig) ] }) export class AppModule {}
注意:配置中的端点标识(此处示例为customPage)必须和fieldSetLevelMapping的根key完全一致,否则字段映射规则不会生效
3. 自定义服务调用已注册的端点
在你开发的自定义页面数据服务中,使用Spartacus内置的OccEndpointsService来拼接请求地址,不要硬编码接口路径,确保参数自动替换逻辑和默认页面一致:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { OccEndpointsService } from '@spartacus/core'; import { Observable } from 'rxjs'; import { CustomPageWsDTO } from './models/custom-page.dto'; @Injectable({ providedIn: 'root' }) export class CustomPageService { constructor( private http: HttpClient, private occEndpoints: OccEndpointsService ) {} loadPageData(pageCode: string, fieldLevel: string = 'LIST'): Observable<CustomPageWsDTO> { const requestUrl = this.occEndpoints.buildUrl('customPage', { urlParams: { pageCode }, queryParams: { fields: fieldLevel } }); return this.http.get<CustomPageWsDTO>(requestUrl); } }
4. 效果验证
完成上述配置后,Spartacus会自动按照PLP的规则处理字段映射:请求时会根据你指定的字段层级自动拼接fields参数,后端接收到参数后按照你开发的Populator逻辑返回对应层级的WSDTO数据,Network面板中的返回格式就会和PLP页面完全一致。
内容的提问来源于stack exchange,提问作者Rabia
相关产品推荐
相关产品推荐

