我是Promises的新手,我发现我必须使用Promises从本地存储中获取保存的信息。我想在我设置之前调用post请求
params.set('az_key', data)
。我怎么解决这个问题?尝试了Promise中的return语句,但这会导致错误。
public call(params : URLSearchParams) {
this.storage.getAZKey().then(data=>{
console.log(data);
params.set('az_key', data);
console.log("AZ-Key: " + params.get("az_key"));
})
console.log("Token for XXrequest: " + params.get("az_key")); // gives me null
return this.http
.post("http://localhost:8080/Info", params)
.map(res => res.text())
}
}
答案 0 :(得分:3)
您不需要承诺从本地存储中获取内容。
设置内容:
localStorage.setItem("username", "John");
获得一些东西:
localStorage.getItem("username");
注意:您只能设置和获取字符串。
参考:https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
但是对于你的异步问题;你设置你的param之前“可能”调用你的帖子请求是正确的,因为它们是异步函数。
一种方法可能是链接这些异步函数,如:
public call(params : URLSearchParams) {
return this.storage.getAZKey().then(data=>{
console.log(data);
params.set('az_key', data);
console.log("AZ-Key: " + params.get("az_key"));
}).then(data=>{
console.log("Token for XXrequest: " + params.get("az_key")); // gives me null
return this.http
.post("http://localhost:8080/Info", params)
.map(res => res.text())
})
}
当你使用这种方法时:
this.servletService.call(params).then((obs)=>{
obs.subscribe(
(data)=>{
console.log(data);
},
(err)=>{console.log(err);})
});