gpt4 book ai didi

javascript - 来自 API 的变量未传递到 Angular 中的本地存储

转载 作者:行者123 更新时间:2023-12-01 16:17:20 25 4
gpt4 key购买 nike

我正在开发一个预订系统,用户可以在该系统中传递航类数据——日期、城市、乘客数量。并根据选择,通过 Skyscanner API 计算最便宜的航线价格。之后,所有具有赋值的变量都被传递到 localStorage 中。但这不适用于价格值,即使 API 工作正常并在 console.log 中检查时显示该值。我尝试将它绑定(bind)到另一个变量并将第二个变量传递到本地存储,但也没有成功。

提前感谢您帮助解决这个谜团,因为我没有想法和仔细检查:)

STACKBLITZ:https://stackblitz.com/edit/local-storage-data

组件.ts

  public numberOfPassengers: number = 1;
public departureDate: any;
public returnDate: any;
public departureAirport: string;
public destinationAirport: string;
public showStorage: any;
public departureAPI;
public arrivalAPI;
public basePrice: number; //should but does not get into localstorage

getConnection() {
fetch(
`https://cors-anywhere.herokuapp.com/https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/browsequotes/v1.0/PL/PLN/en-US/${this.departureAPI}/${this.arrivalAPI}/${this.departureDate}?inboundpartialdate=${this.returnDate}`,
{
method: "GET",
headers: {
"x-rapidapi-host":
"skyscanner-skyscanner-flight-search-v1.p.rapidapi.com",
"x-rapidapi-key": "4ffdf62c6bmshfb49ff445025abep1e2116jsn7d7aae645a00",
},
}
)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data)
this.basePrice = data.Quotes[0].MinPrice;
console.log("basePrice " + this.basePrice)
})
.catch((err) => {
console.log(err);
});

}

this.getConnection();

let dataStorage = {
departureDate: this.departureDate,
returnDate: this.returnDate,
departureAirport: this.departureAirport,
arrivalAirport: this.destinationAirport,
passengersNumber: this.numberOfPassengers,
departureAPI: this.departureAPI,
arrivalAPI: this.arrivalAPI,
basePrice: this.basePrice //this part is not getting into local storage

};
localStorage.setItem("flightdetails", JSON.stringify(dataStorage));
this.showStorage = JSON.parse(localStorage.getItem("flightdetails"));
}
}

最佳答案

因为在从 getConnection() 得到响应之前,您将 dataStorage 设置为 localStorage。

这正在发生:

  1. 用户点击按钮(到摘要)
  2. 调用了saving()方法
  3. saving 调用 getConnection() 并且这个函数是发出 HTTP 请求,但我们不知道响应何时到达...
  4. 您正在使用 localStorage.setItem()
  5. 将您的值保存到 localStorage
  6. 我们不知道什么时候,但 API 已经响应,我们正在设置 this.basePrice 值。但是我们已经将该值保存到 localStorage。

您必须等到从 API 获得响应,然后再进行设置。

总结:收到basePrice后应该这样保存

  .then((data) => {
console.log(data)
this.basePrice = data.Quotes[0].MinPrice;
console.log("basePrice " + this.basePrice);
localStorage.setItem("flightdetails", dataToBeSaved);
})

或者为了更清楚,您可以使用 async/await。我已经 fork 了您的项目并做了一些更改:

With async / await

关于javascript - 来自 API 的变量未传递到 Angular 中的本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62551542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com