我有一个抓取失败并获取JWT令牌,然后将其保存到本地存储。这工作。Aurelia - 两个“Fetches”的问题,其中第二个完成并在新页面呈现后加载localStorage
然后,我已经将“.then”链接到初始抓取并通过称为另一个抓取的函数去获取API的用户名和密码,然后将其保存到本地存储。
最后的“.then”将根重置为新的根。 (工作)...和JWT和登录的第一localStorage保存也是在setRoot调用开始之前完成的,但是...
我的问题是我找到用户名保存到localStorage从第二次提取发生在新的根页面运行它的构造函数之后,它将尝试从localStorage获取用户名。 localStorage中的“用户名”尚未设置,因为第二次抓取尚未完成...
我如何确保在重置根之前,我的所有抓取和所有保存到localStorage都已成功保存?
这是我的login.ts文件,我在这里进行初始获取。
login(username: string, password: string) {
this.userLogin.Username = username;
this.userLogin.Password = password;
// Lets do a fetch!
const task = fetch("/api/jwt", {
method: "POST",
body: JSON.stringify(this.userLogin),
headers: new Headers({ 'content-type': 'application/json' })
})
.then(response => response.json())
.then(data => {
console.log("data - in FETCH: ", data);
localStorage.setItem(this.TOKEN_KEY, JSON.stringify(data));
localStorage.setItem(this.LOGGED_IN, JSON.stringify("authenticated"));
})
.then(() => {
this.saveUserDetail();
})
.then(() => {
console.log(" before redirect USERNAME_KEY): ", localStorage.getItem(this.USERNAME_KEY));
this.router.navigate('/', { replace: true, trigger: false });
this.router.reset();
this.aurelia.setRoot('app/app/app');
})
.catch(error => {
this.clearIdentity();
});
你可以看到,我在第三个“然后”,并在fouth“然后”呼this.saveUserDetail()我做了aurelia.setRoot(“...”)。
这是我的this.saveUserDetail()函数与第二个提取。
saveUserDetail() {
const session = this.getIdentity();
if (!session) {
throw new Error("No JWT present");
}
const token = session.access_token;
const headers = new Headers({
Authorization: `bearer ${token}`,
"Content-Type": "application/json; charset=utf-8"
});
const task = fetch("/api/jwt/userDetail", {
method: "GET",
headers
})
.then(response => response.json())
.then(data => {
try {
console.log("data.stringify: ", JSON.stringify(data));
localStorage.setItem(this.USERNAME_KEY, data.username);
localStorage.setItem(this.USERROLES_KEY, data.role);
} catch (Error) { }
console.log("localStorage.getItem(this.USERNAME_KEY): ", localStorage.getItem(this.USERNAME_KEY));
});
}
我在印象之下我应该回到API的用户名。也许我可以做到一次获取等有没有办法我可以有localStorage加载一切之前,我做了一个“aurelia.setroot()?
这很有效。采取相同的方法,但在提取完成后我并不知道“返回任务”。最后,我在新的根目录中显示用户名。谢谢。 – si2030