Magento2 – Fix Can’t Get Customer Data on Frontend

frontendjavascriptknockoutjsmagento2

I'm trying to get the customer data on on the frontend of a custom template similar to how it is done in:

app/code/Magento/Theme/view/frontend/templates/html/header.phtml

As described in this article.

This is what I have:

<h2>test2:
    <span data-bind="text: customer().firstname">
</h2>
<script type="text/x-magento-init">
        {
            "*": {
                "Magento_Ui/js/core/app": {
                    "components": {
                        "customer": {
                            "component": "Magento_Customer/js/view/customer"
                        }
                    }
                }
            }
        }
</script>

But it throws this error in the browser console:

knockout.js:3012 Uncaught ReferenceError: Unable to process binding
"text: function (){return customer().firstname }"

Best Answer

You're missing the scope, try this:

<div data-bind="scope: 'customer'">
    <h2>test2:
        <span data-bind="text: customer().firstname">
    </h2>
</div>

A complete example using the scope example-scope taken from this answer.

 Template

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "example-scope": {
                    "component": "Magento_Cms/js/knockout-example",
                    "exampleMessage": "<?= __('Hello Magento Stack Exchange!') ?>"
                }
            }
        }
    }
}
</script>

<div data-bind="scope: 'example-scope'">
    <h2 data-bind="text: message"></h2>
    <!-- ko template: getTemplate() --><!-- /ko -->
</div>

 Component

define(['ko', 'uiComponent'], function(ko, Component) {
    'use strict';

    return Component.extend({
        defaults: {
            exampleMessage: 'Hello?',
            template: 'Magento_Cms/test'
        },

        initialize: function() {
            this._super();
            console.log(this.exampleMessage);
            this.message = ko.observable(this.exampleMessage);
        }
    });
});
Related Topic