我这里有两种方法,
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)))
}
}
当我调用此方法const accessToken = this.getAccessToken();
如果令牌在cookie中然后它工作正常,但如果我需要发送Ajax调用来获取令牌,我的accessToken是未定义的show然后突然它会抛出错误
ExpressionChangedAfterItHasBeenCheckedError:表达式已更改 在检查之后。
答案 0 :(得分:1)
我认为你需要在你的功能中实现回调。我对你的方法进行了修改。
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);
}