3
我是新來的打字稿,我無法找到替代方案來優化一行代碼,如下所示。我需要過濾,從我傳遞給promise.then()的回調函數得出的數組...上面typescript syntax angular2 promise然後回調
getAllItems(): Promise<MyItem[]> {
return this.http.get(this.itemsUrl).toPromise()
.then(this.extractData)
.catch(this.handleError);
}
getItem(id: number | string): Promise<MyItem> {
var that = this; // i want to avoid to use this...
return this.http.get(this.itemsUrl).toPromise()
// ...just here
.then(function(res) {
return that.extractData(res).filter(h => h.id === +id)[0];
})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
代碼工作很好,但我想用更短(更打字稿我猜)語法實現類似的東西:
getItem(id: number | string): Promise<MyItem> {
return this.http.get(this.itemsUrl).toPromise()
// ... here again
.then(this.extractData => result.filter(h => h.id === +id)[0])
.catch(this.handleError);
}
顯然它不起作用...有什麼建議嗎?謝謝。
感謝的人,非常有幫助。 – user3683782