gpt4 book ai didi

javascript promise 、缓存和 Angular

转载 作者:行者123 更新时间:2023-12-03 09:30:54 24 4
gpt4 key购买 nike

我有一个 Angular 服务,负责从服务器加载项目,然后当在 View 中选择一个项目时,将从项目列表中取出相应的项目并返回到详细信息。

我现在遇到的问题是,重新加载页面时,我的项目尚未加载,因此我的解析失败,导致重新加载失败。

  getItems = (): ng.IPromise<Array<any>> => {
if (this.items != undefined) {
return this.items;
}

return this.$http.get(url).then((result) => {
this.items = result.data['items'];
return this.items;
});
}

getItem= (id: any): ng.IPromise<any> => {

return this.getItems().then(() => angular.forEach(this.items, (item: any) => {
if (item.id === id) {
return item;
}
}));
}

我以为这段代码(getItem)会返回一个项目,但它再次返回整个集合。我如何修复我的代码以让我返回单个项目?

最佳答案

如果您可以使用 es6-shim:

getItem= (id: any): ng.IPromise<any> => {
return this.getItems().then(() => this.items.find( (item: any) => {
return item.id === id;
}));
}

或者你可以使用

getItem= (id: any): ng.IPromise<any> => {
return this.getItems().then(() => this.items.filter( (item: any) => {
return item.id === id;
})[0]);
}

关于javascript promise 、缓存和 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31512026/

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