magento2 check if customer is logged in or not in knockout template
You need to pass dependency of customer object, 'Magento_Customer/js/model/customer',
define(
[
'ko',
'jquery',
'Magento_Customer/js/model/customer',
'mage/translate'
],
function (ko,jquery, customer,$t) {
'use strict';
return Component.extend({
isCustomerLoggedIn: customer.isLoggedIn, /*return boolean true/false */
initialize: function() {
this._super();
/* check using below method */
var isLoggedIn = this.isCustomerLoggedIn();
}
});
}
Now you can check it using customer.isLoggedIn() returns boolean value.
define(
[
'ko',
'jquery',
'Magento_Ui/js/form/element/abstract',
'mage/url',
'Magento_Customer/js/customer-data',
'Magento_Customer/js/model/customer',
'mage/translate'
],
function (Component,storage,ko,jquery,Abstract, url, customerData, customer,$t) {
'use strict';
return Component.extend({
message: function() {
loggedMessage : $t('Welcome, %1!')
},
htmlLoggedMessage: ko.observable(),
isLoggedIn: ko.observable(),
isCustomerLoggedIn: customer.isLoggedIn,
customer: ko.observable({}),
initialize: function() {
this._super();
if(this.isCustomerLoggedIn()) {
this.isLoggedIn(true);
}
this.checkCustomerLocalStorage();
},
/**
* Check customer localstorage
*/
checkCustomerLocalStorage: function () {
var self = this;
var time = setInterval(function () {
self.customer = customerData.get('customer');
if (localStorage["mage-cache-storage"] != '{}') {
clearInterval(time);
}
if (self.customer().fullname) {
var name = self.customer().fullname;
var message = self.message.loggedMessage.replace('%1', name);
self.htmlLoggedMessage(message);
}
}, 1000);
}
});
}