Magento 2 – Using this.getUrl() in JavaScript

magento2

Building a custom module, where i need to make ajax call. I search on magento project i get

this.getUrl()

Method being used in

vendor/magento/module-checkout/view/frontend/web/js/model/resource-url-manager.js

define(
[
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/model/url-builder',
    'mageUtils'
],
function(customer, urlBuilder, utils) {
    "use strict";
    return {
        getUrlForTotalsEstimationForNewAddress: function(quote) {
            var params = (this.getCheckoutMethod() == 'guest') ? {cartId: quote.getQuoteId()} : {};
            var urls = {
                'guest': '/guest-carts/:cartId/totals-information',
                'customer': '/carts/mine/totals-information'
            };
            return this.getUrl(urls, params);
        },

In order to use this.getUrl() in my custom module, i have added mageUtils and url-builder to my widget js file but don't work.

I would like to know where is it defined ? or how can i use that method ?

Best Answer

getUrl() function defined in

vendor/magento/module-checkout/view/frontend/web/js/model/resource-url-manager.js

getUrl: function(urls, urlParams) {
            var url;

            if (utils.isEmpty(urls)) {
                return 'Provided service call does not exist.';
            }

            if (!utils.isEmpty(urls['default'])) {
                url = urls['default'];
            } else {
                url = urls[this.getCheckoutMethod()];
            }
            return urlBuilder.createUrl(url, urlParams);
        },

You can use this function just add file path in your define function.

Related Topic