我有一个 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/