我有一个angular服务,负责从服务器加载项目,然后当一个项目在视图中被选中时,相应的项目将从项目列表中取出并返回到detail
我现在遇到的问题是,当重新加载页面时,我的项目尚未加载,因此我的解析失败,导致重新加载失败。
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]);
}