Magento – Calling loader show/hide function in magento 2 js template

ajaxmagento2

I have been creating a custom component to load cart items in Magento 2 modal widget. I have to show a loader only in a custom div tag. Here is the code of my custom js component.

 define([
        'ko',
        'uiComponent',
        'mage/url',
        'mage/storage',
    ], function (ko, Component, urlBuilder, storage) {
        'use strict';
        var self = this;
        return Component.extend({
            defaults: {
                template: 'RLTSquare_PartialCheckout/cart'
            },

            //models are defined here
            cartItemsList: ko.observableArray(),
            shouldShowLoader: ko.observable(false),

            initialize: function () {
                self = this;
                this._super();
                this.loadList();
            },
            loadList: function () {
                self.shouldShowLoader(true);
                var serviceUrl = urlBuilder.build('rltsquare_partialcheckout/cart/get');
                return storage.post(
                    serviceUrl, ''
                ).done(
                    function (response) {
                        self.cartItemsList.removeAll();
                        var list = response;
                        for (var i = 0; i < list.length; i++) {
                            self.cartItemsList.push(list[i]);
                        }
                        self.shouldShowLoader(false);
                    }
                ).fail(
                    function (response) {
                        self.shouldShowLoader(false);
                        alert(response);
                    }
                );
            }
        });
    });

Is there a way I can get magento 2 loader in my .html file or .js file?
I have already bound it to my .html template as:

<div data-role="loader" data-bind="visible: shouldShowLoader" class="loading-mask" style="position: absolute;">
    <div class="loader">
        <img src="http://127.0.0.1:8888/m2-2.2/pub/static/version1513844156/frontend/Magento/luma/en_US/images/loader-1.gif" alt="Loading..." style="position: absolute;">
    </div>
</div>

I already went through mage/loader component defined in M2 but could not find its usage properly.

Is there a way I can get the absolute url of this image in js component?

Best Answer

You can just use following code for show/hide loader

Show loader : jQuery('body').loader('show');

Hide Loader : jQuery('body').loader('hide');

Related Topic