最佳实践是编写您自己的 JS 服务来处理与您的 api 端点的通信。
我们有一个抽象的ApiService 类,你可以继承自。您可以查看CalculatePriceApiService 以获取the platform 中的示例。
对您而言,实现可能如下所示:
class MyPluginApiService extends ApiService {
constructor(httpClient, loginService, apiEndpoint = 'my-plugin') {
super(httpClient, loginService, apiEndpoint);
this.name = 'myPluginService';
}
myCustomAction() {
return this.httpClient
.get('my-custom-action', {
headers: this.getBasicHeaders()
})
.then((response) => {
return ApiService.handleResponse(response);
});
}
}
请注意,您的 api 服务已预先配置为在构造函数的第一行与您的 my-plugin 端点通信,这意味着在您发出的所有以下请求中,您都可以使用相对路由路径。
请记住,抽象 ApiService 将负责解析用于请求的配置。特别是这意味着 ApiService 将使用正确的 BaseDomain 包括子文件夹,并且它将自动使用您的商店软件版本支持的 apiVersion。这意味着每次有新的 api 版本可用时,ApiService 在路由中使用的 apiVersion 都会增加,这意味着您需要在 api 版本的后端路由注释中使用通配符。
最后请记住,您需要注册该服务。那是documented here。
对你来说,这可能看起来像这样:
Shopware.Application.addServiceProvider('myPluginService', container => {
const initContainer = Shopware.Application.getContainer('init');
return new MyPluginApiService(initContainer.httpClient, Shopware.Service('loginService'));
});