I need to get the customer email in homepage in a script.
Googling around I find mentions of window.customerData variable, but is always undefined (perhaps removed in latest versions?)
So at first I tried this:
require([
'Magento_Customer/js/model/customer',
...
but it fails with error:TypeError: can't convert undefined to object somewhere in customer-addresses.js
Then I tried with:
require([
'Magento_Customer/js/customer-data',
...
and then customerData.get('customer') but it gives me only first and last name or an empty object (even when the user is logged).
Is there a way to obtain the logged user email anywhere outside the checkout page?
1 Answer 1
You need to create a plugin in order to save customer email to the local storage. So, add a frontend plugin configuration in di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Customer\CustomerData\Customer">
<plugin name="additional_section_data" type="Your\Module\Plugin\AddCustomerEmail" />
</type>
</config>
And the plugin will look like this:
<?php
namespace Your\Module\Plugin;
use Magento\Customer\Helper\Session\CurrentCustomer;
class AddCustomerEmail
{
/**
* @var CurrentCustomer
*/
private $currentCustomer;
public function __construct(
CurrentCustomer $currentCustomer
) {
$this->currentCustomer = $currentCustomer;
}
public function afterGetSectionData(\Magento\Customer\CustomerData\Customer $subject, $result)
{
if ($this->currentCustomer->getCustomerId()) {
$customer = $this->currentCustomer->getCustomer();
$result['email'] = $customer->getEmail();
}
return $result;
}
}
More information can be found in a similar question here.
-
Thank you, I ended up by doing something very similar: a custom data section.Mir– Mir2017年11月14日 15:14:06 +00:00Commented Nov 14, 2017 at 15:14
customerData.get('myCustomSection')with the info I needed.