【发布时间】:2020-06-24 18:42:33
【问题描述】:
我正在开发一个预订系统,用户在该系统中传递航班数据 - 日期、城市、乘客人数。并根据选择,通过 Skyscanner API 计算最便宜的路线价格。之后,所有赋值的变量都被传递到 localStorage。但这不适用于价格值,即使 API 工作正常并在 console.log 中检查时显示值。我尝试将它绑定到另一个变量并将第二个变量传递到本地存储,但也没有成功。
在此先感谢您帮助解决这个谜团,因为我没有想法并仔细检查:)
堆栈闪电战: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"));
}
}
【问题讨论】:
-
我做了 window.localStorage.setItem("flightdetails", JSON.stringify(dataStorage)); this.showStorage = JSON.parse(window.localStorage.getItem("flightdetails"));但这并没有解决问题。
-
您的 basePrice 出现控制台错误。没有报价。并且系统出现故障。因此,如果我进行硬编码 basePrice: 4 。该值在 localStorage 中。您需要检查您的退货数据是否有价值,或者报价是否存在于给定的路线和日期。
-
嗯,感谢您的反馈,但我刚刚检查并获得了带有“basePrice 1304”的控制台日志 - 也许 API 有问题?
-
好的,我现在看到你的问题了。是的,但检查了一些没有提供报价或基本价格的日期。但您的问题出在 getConnection 中。你在里面有一个承诺。但是您将在取回值之前保存本地存储。因此,如果您第二次单击 ToSummary 2 次,您会在 localstorage 中获得正确的数字,因为 this.basePrice 中有一个值。
标签: javascript angular local-storage fetch