Reputation: 16367
I have 2 methods here ,
private getAccessToken() {
let token = this.cookie.get(this.accessTokenName);
if (typeof token == "undefined") {
this.rest.get('m2/token')
.then((response) => {
if (response.token) {
this.cookie.put(this.accessTokenName, response.token);
token = response.token;
return token;
};
});
} else {
return token;
}
}
private fetchStores() {
const accessToken = this.getAccessToken();
if (!accessToken) {
this.core.notify('Error - Fail to connect with GWA,Try again!',0);
} else {
this.rest.get(`m2/store/?${this.accessTokenName}=${this.getAccessToken()}`).then((stores) => console.log('stores', (stores)))
}
}
when I call this method const accessToken = this.getAccessToken();
If token is in cookie then it works fine , but if I need to send Ajax call to get token , My accessToken is undefined show and then suddenly it throws error
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Upvotes: 2
Views: 49
Reputation: 12309
I think you need to implement call back in your functionality. I made the changes in your methods.
private getAccessToken(callback) {
let token = this.cookie.get(this.accessTokenName);
if (typeof token == "undefined") {
this.rest.get('m2/token')
.then((response) => {
if (response.token) {
this.cookie.put(this.accessTokenName, response.token);
token = response.token;
callback(token);
};
})
}else{
callback(token);
}
}
private onGetAccessToken(accessToken){
if (!accessToken) {
this.core.notify('Error - Fail to connect with GWA,Try again!',0);
} else {
this.rest.get(`m2/store/?${this.accessTokenName}=${this.getAccessToken()}`)
.then((stores) => console.log('stores', (stores)))
}
}
private fetchStores() {
this.getAccessToken(onGetAccessToken);
}
Upvotes: 1