Reading list Switch to dark mode

    How to use Service API in Shopware 6

    Updated 30 December 2019

    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 have to 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.
    To learn more about service, there is a link.

    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:

    Searching for an experienced
    Shopware Company ?
    Find out More
    inject: [
       'TestService'
    ]
    methods: {
        saveConfig {
          this.TestService.saveConfig(this.config);
        }
    }

    To learn about the Vue component, there is a link.
    Now you can use your service API in your Vue component.

    I hope It will help you. Thanks

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    4 comments

  • Alex
    • Diwakar Rana (Moderator)
  • Azam
    • Adarsh Shukla (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home