Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5556

How to use Service API in Shopware 6

$
0
0

In this article, we will look into the module which can inject Service API in Shopware 6.

Overview

The main entry point for this purpose is the plugin’s main.js file. It has to be placed into the <plugin root>/src/Resources/app/administration/src the directory in order to be automatically found by Shopware 6.

Creating a service

Firstly, You can create a service file in <plugin root>/src/Resources/app/administration/src /core/service/api .
In my case file name is test-api.service.js.

import ApiService from 'src/core/service/api.service';
class TestService  extends ApiService 
{
  constructor(httpClient, loginService, apiEndpoint = 'test') {
      super(httpClient, loginService, apiEndpoint);
  }

 saveConfig(config) {
   const apiRoute = `${this.getApiBasePath()}/save/config`
   return this.httpClient.post(
         apiRoute,  {
                config: config            
          }, {
                headers: this.getBasicHeaders()
            }
           ).then((response) => {
            return ApiService.handleResponse(response);
        });
    }
}
export default TestService;

Import Service API file and then create a class of your service. In saveConfig function, ${this.getApiBasePath()} is a base path and this.getBasicHeaders() is a header of the request and apiRoute is a path of API controller as described in the above example.

To init this service class, a new script is placed at <plugin root>/src/Resources/app/administration/src /init/api-service.init.js.

See below the code example-
const Application = Shopware.Application;
import TestService from '../../src/core/service/api/test-api.service';
Application.addServiceProvider('TestService', (container) => {
    const initContainer = Application.getContainer('init');
    return new TestService(initContainer.httpClient, container.loginService);
});

Service Injection 

Service is injected into a Vue component and can be referenced in the inject property:

inject: [
   'TestService'
]
methods: {
    saveConfig {
      this.TestService.saveConfig(this.config);
    }
}


Now you can use your service API in your Vue component.

I hope It will help you. Thanks


Viewing all articles
Browse latest Browse all 5556

Latest Images

Trending Articles



Latest Images