2015-07-20 102 views
0

我有一个角度的服务,需要照顾的加载项从服务器,然后当一个项目在视图中被选中,相应的项目将被从项目列表中取出并返回到细节。JavaScript的承诺,缓存和角

的问题我现在是重新加载页面时,我的项目还没有加载,因此我的决心失败,导致设备故障重装。

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)会返回一个单一的项目,但它会再次返回整个集合。我如何修复我的代码让我返回单个项目?

+0

当你调用'getItem'功能? –

+0

getItem从我的路由中的解析调用 – Patrick

+0

在递交给'forEach'的lambda中调用'return'没有用,特别是它不会导致外部函数返回。 '... for'循环是你最好的选择。 –

回答

1

如果你可以使用ES6-垫片:

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]); 
}