Get Shipping Methods in Custom Component at Checkout in Magento 2

checkoutmagento2shippingshipping-methodsuicomponent

Magento 2.0.1.

I have created custom component in checkout, and I want to get inside its js file list of active shipping methods and preselect one of them, according to configuration passed via custom CheckoutConfigProvider.
My component is placed in shipping step node children array.

Problem is getting shipping method list. Firstly I tried to use as dependency magento2/app/code/Magento/Checkout/view/frontend/web/js/model/shipping-service.js and then use method getShippingRates, which actually is used inside magento2/app/code/Magento/Checkout/view/frontend/web/js/view/shipping.js and there it returns shipping methods list. Unfortunately, my js it returns an empty array.

Also, I tried to move my component into children array of shipping adrress node, but it did not help.

In both places, my component js is loaded before shipping.js and returns empty methods array. Has anyone tried to work with shipping methods during checkout loading?

Best Answer

Take a look at:

vendor/magento/module-checkout/view/frontend/web/js/view/cart/shipping-rates.js. We can get the shipping rates list:

shippingRates: shippingService.getShippingRates(),

But, we need to observe the value with initObservable. For example:

    /**
     * @override
     */
    initObservable: function () {
        var self = this;

        this._super();

        this.shippingRates.subscribe(function (rates) {
            self.shippingRateGroups([]);
            _.each(rates, function (rate) {
                var carrierTitle = rate['carrier_title'];

                if (self.shippingRateGroups.indexOf(carrierTitle) === -1) {
                    self.shippingRateGroups.push(carrierTitle);
                }
            });
        });

        return this;
    },
Related Topic